Skip to content

Instantly share code, notes, and snippets.

@bignimbus
Last active April 14, 2017 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bignimbus/e37fd60d862b8baf0664cb67bc656a9a to your computer and use it in GitHub Desktop.
Save bignimbus/e37fd60d862b8baf0664cb67bc656a9a to your computer and use it in GitHub Desktop.

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 %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment