Search code examples
ruby-on-rails-3form-fornested-resources

How to get the form_for working for a nested resource - with a slight twist


I'm looking to have the child model added/edited on it's own form, not within the parent form.

any example I have seen has the child added on the same form as the parent. Since I'm adding the twist of adding/editing on a separate form, I'm wondering if that's why I get the following error:

undefined method `chapters_path'...

routes.rb:

resources :books do
  resources :chapters
end

book.rb:

has_many :chapters

chapter.rb

belongs_to :book

_form.html.erb:

<% form_for [@book, @chapter] do |f| %>

I think I still need to use the nest resource methodology, since I'm wanting to add the child with a url such as books/1/chapters/new - because that would be the proper rails approach, no? or maybe I'm looking at this the wrong way.

Any help greatly appreciated.


Solution

  • ok - I've got it working - in case anyone is interested, here are the adjustments:

    routes.rb

    resources :chapters, :only => [:destroy, :update]
    resources :books do
      resources :chapters, :only => [:create, :edit, :index, :new, :show]
    end
    

    adjustments were also required for some of the redirects in the chapters controller