Does ActiveRecord save a belongs_to association when saving main object?

血红的双手。 提交于 2019-12-19 05:44:59

问题


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?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2231415/does-activerecord-save-a-belongs-to-association-when-saving-main-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!