Does accepts_nested_attributes_for work with belongs_to?

Nick M picture Nick M · Sep 9, 2011 · Viewed 22.8k times · Source

I have been getting all kinds of conflicting information regarding this basic question, and the answer is pretty crucial to my current problems. So, very simply, in Rails 3, is it allowed or not allowed to use accepts_nested_attributes_for with a belongs_to relationship?

class User < ActiveRecord::Base
  belongs_to :organization
  accepts_nested_attributes_for :organization
end

class Organization < ActiveRecord::Base
  has_many :users
end

In a view:

= form_for @user do |f|
  f.label :name, "Name"
  f.input :name

  = f.fields_for :organization do |o|
    o.label :city, "City"
    o.input :city

  f.submit "Submit"

Answer

kid_drew picture kid_drew · Apr 16, 2014

Nested attributes appear to work fine for a belongs_to association as of Rails 4. It might have been changed in an earlier version of Rails, but I tested in 4.0.4 and it definitely works as expected.