Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How to create a new nested resource?

The Getting Started Rails Guide kind of glosses over this part since it doesn't implement the "new" action of the Comments controller. In my application, I have a book model that has many chapters:

class Book < ActiveRecord::Base   has_many :chapters end  class Chapter < ActiveRecord::Base   belongs_to :book end 

In my routes file:

resources :books do   resources :chapters end 

Now I want to implement the "new" action of the Chapters controller:

class ChaptersController < ApplicationController   respond_to :html, :xml, :json    # /books/1/chapters/new   def new     @chapter = # this is where I'm stuck     respond_with(@chapter)   end 

What is the right way to do this? Also, What should the view script (form) look like?

like image 351
Andrew Avatar asked Sep 24 '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]

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.

What is the difference between resource and resources?

Singular routes* are a little different – they are written as singular resource . Declaring a resource or resources generally corresponds to generating many default routes. resource is singular. resources is plural.


1 Answers

First you have to find the respective book in your chapters controller to build a chapter for him. You can do your actions like this:

class ChaptersController < ApplicationController   respond_to :html, :xml, :json    # /books/1/chapters/new   def new     @book = Book.find(params[:book_id])     @chapter = @book.chapters.build     respond_with(@chapter)   end    def create     @book = Book.find(params[:book_id])     @chapter = @book.chapters.build(params[:chapter])     if @chapter.save     ...     end   end end 

In your form, new.html.erb

form_for(@chapter, :url=>book_chapters_path(@book)) do    .....rest is the same... 

or you can try a shorthand

form_for([@book,@chapter]) do     ...same...      
like image 121
dombesz Avatar answered Sep 28 '22 08:09

dombesz