views:

48

answers:

2

Hello,

I have the following rails 3 nested resource:

resources :books do
  resources :authors
end

My authors table has ID | name | book_id

Given I'm at the URL /books/312/authors/new

How do I structure the controller, so that I create a new Author assigned to a book

@author = Book.author.create.(params[:author])

What should the Authors Form new look like?

<%=form_for [Book, Author.new] do |f| %>

thanks

A: 

You want to use inherited resources.

Tass
@Tass. Thanks can you share why? can't I use the standard Nested Resource way with Rails? I hesitate to start adding plugins before I master the default Rails 3 way to get this done.
WozPoz
+2  A: 

In the create action of your author controller:

def create
  @book = Book.find(params[:book_id])
  @author = @book.authors.build(params[:author])

  #rest of your code...

Then in your new author form:

<%= form_for [:book, @author] do |f| %>

Hope that helps!

Sonia
thanks! Trying it now... Do I need to add anything to the Authors NEW Controller? perhaps to pass the book_id?
WozPoz
Also does it have to be .build? Can it be .create?
WozPoz
Just tried it out... After submitting the form on my local machine it hangs for a while and then errors with: ::BusyException: database is locked: INSERT INTO "authors" .... Is my routes.rb file stuff look right?
WozPoz
Take a look at http://blog.mrbrdo.net/2009/10/27/ruby-on-rails-new-vs-create-vs-build/ for a bit about the difference between build and create. I believe you don't need anything extra in your new action, it works fine that way for me! Regarding the last error, I'm not too sure what's going on there...your routing looks fine to me, the problem looks like it goes deeper than the code above.
Sonia