Rails 3: How to create a new nested resource?
Solution 1:
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...
Solution 2:
Try @chapter = @book.build_chapter
. When you call @book.chapter
, it's nil. You can't do nil.new
.
EDIT: I just realized that book most likely has_many chapters... the above is for has_one. You should use @chapter = @book.chapters.build
. The chapters "empty array" is actually a special object that responds to build
for adding new associations.