【问题标题】:Does ActiveRecord save a belongs_to association when saving main object?ActiveRecord 在保存主对象时是否保存了belongs_to 关联?
【发布时间】:2010-02-09 18:22:50
【问题描述】:

如果我有两个模型:

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts
end

如果我这样做:

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

用户是否也被保存并且主键是否正确分配在postuser_id 字段中?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    ActiveRecord belongs_to 关联可以与父模型一起自动保存,但默认情况下该功能处于关闭状态。要启用它:

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

    【讨论】:

    • 很奇怪。我打开了那个标志,和上面一样做仍然给我&gt; post.errors #=&gt; #&lt;OrderedHash {:user_id=&gt;["can't be blank"]}&gt;user.new_record? #=&gt; true。我错过了什么吗?
    • 其实这个功能默认是开启的。您必须将其设置为 false 才能将其关闭,否则将自动保存所有关联。
    • @OdeeOdum:这不是真的,我遇到了这样的问题,在 rails 3 中设置 autosave: true 解决了这个问题。
    • @Fire-Dragon-DoL,实际上这是默认行为。根据 ActiveRecord::AutosaveAssocation 文档,当 :autosave 选项不存在时,将保存新的关联。
    • 来自 ActiveRecord 文档: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.
    【解决方案2】:

    我相信你想要:

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

    换句话说,当保存用户记录时,找出“帖子”关联另一端的所有记录并保存。

    【讨论】:

      【解决方案3】:

      belongs_to API documentation 说(Rails 4.2.1):

      :autosave

      如果为 true,则在保存父对象时始终保存关联对象,如果标记为销毁,则将其销毁。

      如果为 false,则永远不要保存或销毁关联的对象。

      默认只保存关联的 对象,如果它是新记录。

      请注意,accepts_nested_attributes_for 将 :autosave 设置为 true。

      在您的情况下,用户是新记录,因此将自动保存。

      关于accepts_nested_attributes_for的最后一句话也被很多人错过了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        相关资源
        最近更新 更多