开发者

rails nested object form and namespaced controller

i have a nested object like this:

class Work < ActiveRecord::Base
  belongs_to :issue
  belongs_to :author
  has_many :pages, :class_name => 'Work'
  accepts_nested_attributes_for :pages, :allow_destroy => true
end

class Page < ActiveRecord::Base
  belongs_to :work
end

and开发者_如何学JAVA i have a form to create/edit a work, with fields for the nested page object. i followed this post for setting things up, so i'm using a helper so that my form creates a new page when you start out.

module AdminHelper

  def make_work(work)
    returning(work) do |w|
      w.pages.build if w.pages.empty?
    end
  end

end

then, in my form partial i have:

- form_for make_work(@work) do |f|
  ...
  - f.fields_for :page do |page_f|
    = page_f.label :text
    %br
    = page_f.text_area :text

  %p
    = f.submit "Submit"

that displays the fields for the page, but when it's submitted it looks for the create action in the works controller. the create action is in the admin works controller (namespaced), so that breaks.

i try it with the namespaced object, but if i do it this way it doesn't know about pages:

- form_for make_work([:admin, @work]) do |f|
  ...

how do i use the namespace with the nested object form so that it has the pages method, but posts to the namespaced admin/works controller?


I think you should have:

fields_for :pages do |page_f|
                ^

Also check in generated html if submit path for form is correct. In your case it should be something like:

/admin/works/3

EDIT:

Example for fields_for:

<% form_for @person do |person_f| %>
  <% person_f.fields_for :emails do |email_f| %>
     <%= email_f.text_field :address %>
  <% end %>
<% end %>

and it is for relationship like:

class Person
  has_many :emails
end

Make sure you didn't iterate over pages like this:

<% @work.pages.each do |page| %>
...
  <% fields_for :page do |p| %>
...


This might not be the best solution, but you could just drop your make_work helper, target the form with [:admin, @work] (I can never remember that syntax) and just do the w.pages.build call in your controller, e.g.:

controller:

@work = Work.new
@page = @work.pages.build

view:

-form_for [:admin, @work] ...
  -f.fields_for @page ...


turns out i had something wrong in my work model. i had:

class Work < ActiveRecord::Base
  belongs_to :issue
  belongs_to :author
  has_many :pages, :class_name => 'Work'
  accepts_nested_attributes_for :pages, :allow_destroy => true
end

the 'class_name => 'Work'' was causing it to look for the 'text' object on the Work class, rather than the Page class. now it works!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜