Last Updated: February 25, 2016
·
1.012K
· benburton

Routing resources with and without member blocks

Normally, I declare Rails routes to actions for singular resources in a member block as follows:

resources :blog_posts do
  member do
    post 'tag'
  end
end

this causes rake routes to produce the following:

tag_blog_post POST   /blog_posts/:id/tag(.:format)  blog_posts#tag

But today I came across a situation in which the action for a singular resource was not in a member block:

resources :blog_posts do
  post 'tag'
end

which caused rake routes to produce this instead:

blog_post_tag POST   /blog_posts/:blog_post_id/tag(.:format) blog_posts#tag

There are two important differences in the produced routes:

  • When in the member block, the resource is identified simply by the :id parameter, whereas without the member block a more verbose :blog_post_id parameter, which includes the model name, is required.

  • When in the member block, the action comes at the beginning of the route helper (tag_blog_post) whereas without the member block it is prepended (blog_post_tag).

The differences are interesting. I wonder if there is a reason why they operate this way, or if it's simply a curious side effect of the implementation.

1 Response
Add your response

Thinking back. I seem to remember running into this a couple times before. Essentially, all seems right, then you go to use a route in your view -- say projectpath(@project). It will throw an error as it doesn't know what to do with the ivar. If you then change the route to projectpath(@project.id) it will work. It must use the :member option to infer what attribute it should use for the route?

over 1 year ago ·