开发者

Is there a way to automatically create a plural route for index and singular for everything else?

When dealing with a collection resource, I like to use the plural for the index (ie. list) page (viewing many objects), and singular for the other pages (create/update/delete one object).

In order to do so, I seem to have to create my routes like so:

map.objects 'objects.:format', :controller => :object, :action => :index, :conditions => { :method => :get }
map.resources :object, :controller => :object, :except => :index

This creates routes like so:

     objects GET    /objects(.:format)          {:action=>"index", :controller=>"object"}
object_index POST   /object(.:format)           {:action=>"create", :controller=>"object"}
  new_object GET    /object/new(.:format)       {:action=>"new", :controller=>"object"}
 edit_object GET    /object/:id/edit(.:format)  {:action=>"edit", :controller=>"object"}
      object GET    /object/:id(.:format)       {:action=>"show", :controller=>"object"}
             PUT    /object/:id(.:format)       {:action=>"update", :controller=>"object"}
             DELETE /object/:id(.:format)       {:action=>"destroy", :controller=>"object"}

It works, but it seems like I'm using an extra line in my routes file (to explicitly specify the index route) when I shouldn't hav开发者_运维问答e to. Is there a way to do what I want in one route? Or, alternately, is there a reason not to route this way?


The only reason other than "normal REST says don't" to not have the "object" be a resource under "objects" is search engines.

Google will notice that you have "recipes" and then recipes under "recipes", and give you those cool sitelinks:

Is there a way to automatically create a plural route for index and singular for everything else?

Google's Webmaster Guidelines say, in the first item under design and content guidelines, "Make a site with a clear hierarchy and text links."


RESTful routing is designed in such a way that you're scoping down what it is you want to do. Say you go to http://example.com/objects. Here, you're telling the site you want a list objects.

Now when you go to http://example.com/objects/2 you're telling it you want to see the object with identifier of 2 in that list (or resource) of objects.

Finally, when you go to http://example.com/objects/2/edit you're saying you want to find the object again with identifier of 2 but this time you would like to edit it rather than view it.

By going against the grain like you have suggested in routing helpers you will be causing a tremendous amount of unnecessary pain for yourself and for anybody else reading your code.

However if you do choose to go this path (again, I advise against it) then yes, defining two routes is the only way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜