Say you have a model that has_many
of another model through a third, intermediary model.
class Foo
has_many :bar_infos
has_many :bars, through: :bar_infos
accepts_nested_attributes_for :bar_infos
end
class BarInfo
belongs_to :bar
belongs_to :foo
accepts_nested_attributes_for :bar
end
class Bar
has_one :foo, through: :bar_info
has_one :bar_info
end
Now say you have a form that POSTs a new instance of Foo
with nested attributes for new instance of BarInfo
and Bar
. It is important that the nesting be:
# good
foo
bar_info_attributes
bar_attributes
# bad
foo
bar_attributes
bar_info_attributes
This is due to how ActiveRecord sets and initializes foreign keys in this type of relationship.
Ex:
class FooController
def new
@foo = Foo.new
end
end
<!-- new.html.erb -->
<%= form_for @foo, url: create_foo_path, method: :post do |f| %>
<%= f.text_field :foo_name %>
<%= f.fields_for :bar_info_attributes do |info| %>
<%= info.text_field :info_name %>
<%= info.fields_for :bar_attributes do |bar| %>
<%= bar.text_field :bar_name %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>