Using accepts_nested_attributes_for with single table inheritance
I have a model Post
which belongs_to
one Section
. There are two different Section
subclasses and I use STI to implement different behavior for each of them. In the Post
form I would like to have a tab for each Section
. The tab will let the user either A) Pick from an existing Section
using a <sel开发者_如何学运维ect>
or B) Let the user create a new Section
. I would like to know how to use accepts_nested_attributes_for
and fields_for
or whatever is required to get this done The Rails Way.
Any advice is greatly appreciated. Thanks.
Assuming the tabs correspond to the two subclasses
class Post
# the two subclasses. Each instance will only be using one or the other
belongs_to :section_foo
belongs_to :section_bar
accepts_nested_attributes_for :section_foo
accepts_nested_attributes_for :section_bar
end
And in the view (probably once per tab)
= form_for @post do |f|
= f.select :section_id, SectionFoo.all # etc
= fields_for @post.build_section_foo do |s|
= s.text_field :bla_bla_bla
That should get you 85% of the way there. You might need some :reject_if bidness on the accepts_* to avoid creating a new section and assigning an old section.
精彩评论