11

If I have two models:

class Post < ActiveRecord::Base
  belongs_to :user
end

and

class User < ActiveRecord::Base
  has_many :posts
end

If I do:

post = Post.new
user = User.new
post.user = user
post.save

Does the user get saved as well and the primary key properly assigned in post's user_id field?

agentofuser
  • 8,987
  • 11
  • 54
  • 85

3 Answers3

21

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

class Post < ActiveRecord::Base
  belongs_to :user, :autosave => true
end
Neal
  • 4,468
  • 36
  • 33
Josh Delsman
  • 3,022
  • 1
  • 18
  • 28
  • 2
    Weird. I turned that flag on, and doing the same as above still gives me `> post.errors #=> #["can't be blank"]}>` and `user.new_record? #=> true`. Am I missing something? – agentofuser Feb 09 '10 at 19:23
  • 4
    Actually the functionality is **on** by default. You must set it to false in order to turn it off, otherwise all associations will be saved automatically. – Ode Oct 03 '12 at 17:01
  • 1
    @OdeeOdum: That's not true, I had a problem like this and setting autosave: true in rails 3 fixed the issue. – Francesco Belladonna Mar 03 '13 at 18:37
  • @Fire-Dragon-DoL, Actually it is the default behavior. According to the ActiveRecord::AutosaveAssocation documentation When the :autosave option is not present new associations are saved. – Ode Mar 04 '13 at 21:27
  • Mhhh, I need to check, because I tried without it and it wasn't working. When I added the autosave option it started working fine, and I didn't change anything else meanwhile. – Francesco Belladonna Mar 04 '13 at 22:57
  • 6
    From the ActiveRecord docs: `Note that autosave: false is not same as not declaring :autosave. When the :autosave option is not present then new association records are saved but the updated association records are not saved.` – Christian Jun 30 '13 at 03:04
8

I believe you want:

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

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

cschille
  • 113
  • 1
  • 5
2

The belongs_to API documentation says (Rails 4.2.1):

:autosave

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

If false, never save or destroy the associated object.

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

Note that accepts_nested_attributes_for sets :autosave to true.

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

The last sentence about accepts_nested_attributes_for is also missed by many.

lulalala
  • 17,572
  • 15
  • 110
  • 169