Rails 3: How to create a new nested resource?

The Rails Getting Started Guide , looking into this part, as it does not implement the "new" action of the comment 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 the 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 does the script view (form) look like?

+63
ruby-on-rails ruby-on-rails-3
Sep 24 '10 at 4:25
source share
3 answers

You must first find the appropriate book in your main controller in order to build a chapter for it. You can perform the following actions:

 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 shorthand

 form_for([@book,@chapter]) do ...same... 

Hope this helps.

+119
Sep 28 '10 at 11:15
source share

Try @chapter = @book.build_chapter . When you call @book.chapter , it is zero. You cannot do nil.new .

EDIT: I just realized that the book most likely has several chapters ... above for has_one. You should use @chapter = @book.chapters.build . The "empty array" chapters are actually a special object that responds to build to add new associations.

+6
Sep 24 '10 at 4:51
source share

Perhaps unrelated, but from this question you can come here to see how to do something a little different.

Suppose you want to make Book.new(name: 'FooBar', author: 'SO') , and you want to break some metadata into a separate model called readable_config , which is polymorphic and stores name and author for several models.

How do you take Book.new(name: 'FooBar', author: 'SO') to build the Book model, as well as the readable_config model (which I might mistakenly call a "nested resource")

This can be done like this:

 class Book < ActiveRecord::Base has_one :readable_config, dependent: :destroy, autosave: true, validate: true delegate: :name, :name=, :author, :author=, :to => :readable_config def readable_config super ? super : build_readable_config end end 
+1
Nov 20 '15 at 10:16
source share



All Articles