Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: getting the 'new' path for a nested resource

I have a nested resource which appears like so in my routes:

resource :reviews do
  resource :entries
end

I'm trying to create a link for a new entry path like so:

<%= link_to "New Entry", new_review_entry_path(@review) %>

Unfortunately, I keep getting this error message:

undefined method `new_review_entry_path' for #<#<Class:0x5150d78>:0x483c798>

I checked rake routes, and it turns out that the route should be pluralized into:

new_reviews_entries_path(@review)

Unfortunately, when I do that, then I get an odd url:

/reviews/entries/new.1

Obviously, that doesn't work, either. Any idea what's going on here?

like image 879
nullnullnull Avatar asked Jan 20 '13 22:01

nullnullnull


People also ask

How do I create a nested route in Rails?

In a nested route, the belongs_to (child) association is always nested under the has_many (parent) association. The first step is to add the nested routes like so: In the above Rails router example, the 'index' and 'show' routes are the only nested routes listed (additional or other resources can be added).

What are nested routes in Rails?

Nested resources in rails give us the ability to document parent/child relationships directly in our routes. Here we have the parent (Coffee) and the child(Review) taken from the two models User and Review. Nested routes are another way of capturing these relationships through your routing.

How do you get a Rails route?

Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.


1 Answers

It's resources, not resource. Your first try was the right one ;)

resources :reviews do
    resources :entries
end

You should use resource when the resource is "unique". For instance, if a user has one profile, you would do:

resources :users do
    resource :profile
end
like image 83
Robin Avatar answered Sep 27 '22 19:09

Robin