Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Routing - :resource_id vs :id

In my routes.rb:

resources :posts do
    get "test"
end

This produces the usual RESTful routes with /post/:id/.... However, I also get /post/:post_id/test.

Now my problem is that sometimes the parameter is named :id and sometimes it is :post_id. How can I make it uniform?

Thank you!

like image 330
Denny Avatar asked Jun 25 '11 17:06

Denny


People also ask

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

What is the difference between resources and resource in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.

How do Rails routes work?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

What is namespace in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.


2 Answers

Specify :on => :member, otherwise it is acting as a nested resource.

resources :posts do
    get 'test', :on => :member
end
like image 181
Felix Avatar answered Oct 26 '22 22:10

Felix


You shouldn't make it uniform. It's :id when it's the target resource and :post_id when it is the parent of some other target resource (i.e. nested resources). This is a Rails convention.

like image 29
d11wtq Avatar answered Oct 26 '22 23:10

d11wtq