[ACCEPTED]-Does ActiveRecord save a belongs_to association when saving main object?-associations

Accepted answer
Score: 21

ActiveRecord belongs_to associations have the ability 3 to be autosaved along with the parent model, but 2 the functionality is off by default. To 1 enable it:

class Post < ActiveRecord::Base
  belongs_to :user, :autosave => true
Score: 8

I believe you want:

class User < ActiveRecord::Base
    has_many :posts, :autosave => true

In other words, when 3 saving a User record, seek out all records 2 on the other side of the 'posts' association 1 and save them.

Score: 2

The belongs_to API documentation says (Rails 4.2.1):


If true, always 9 save the associated object or destroy it 8 if marked for destruction, when saving the 7 parent object.

If false, never save or destroy 6 the associated object.

By default, only save 5 the associated object if it’s a new record.

Note 4 that accepts_nested_attributes_for sets 3 :autosave to true.

In your case user is new 2 record so it will be auto saved.

The last 1 sentence about accepts_nested_attributes_for is also missed by many.

More Related questions