Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 3: link_to create new nested resource?

I am trying to make a link to create a new nested resource in my Rails 3 application, but I can't figure it out. What is the syntax to link to a new nested resource

Solution:

Make sure you have your resources properly nested in your routes file.

resources :books do
  resources :chapters
end

Then in your view script you can call it like this:

<%= link_to 'New Chapter', new_book_chapter_path(@book) %>

The Rails Guide on Routing was quite helpful.

Note: if you get a message like Couldn't find Book without an ID, the problem isn't the link, it's the code in your controller.

def new
  @book = Book.find(params[:book_id]) #instead of :id
  @chapter = @book.chapter.new
  respond_with(@chapter)
end
like image 707
Andrew Avatar asked Sep 23 '10 04:09

Andrew


People also ask

What is a nested resource Rails?

Rails Nested Resources Nested routes are another way of capturing these relationships through your routing. This means that our URLs will look aesthetically pleasing and not a random string of numbers and characters. resources :coffees do. resources :reviews, only: [:new, :index, :show] end.

What is the difference between resource and resources 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.

What nested resources?

Nesting resources provide REST API consumers an easy and efficient way to manage data by allowing the consumer to send and receive only the required object. The nested resource must be a business object, that is, it must still represent a complete business object.


1 Answers

make changes in routes as

map.resources :books do |book|
    book.resources :chapters
end

and then use this

link_to new_book_chapter_path(@book)

You can also use this link to understand the concept better Nested Routes

like image 132
Rohit Avatar answered Nov 10 '22 04:11

Rohit