【问题标题】:habtm relationship does not support :dependent optionhabtm 关系不支持 :dependent 选项
【发布时间】:2010-05-10 00:33:36
【问题描述】:

HABTM 关系确实不支持:dependent 选项吗?

class Person < ActiveRecord::Base
  has_and_belongs_to_many :posts, :dependent => :destroy
end

我正在尝试 rails edge。

【问题讨论】:

标签: ruby-on-rails has-and-belongs-to-many


【解决方案1】:

如果你想保持简单的has_and_belongs_to_many 关联,你可以添加这个:

class Person < ActiveRecord::Base
  has_and_belongs_to_many :posts
  before_destroy { posts.clear }
end

这将清除该person 的所有条目的连接表。注意:这只会从连接表中删除记录,它不会破坏posts(如果它是双向has_and_belongs_to_many 是有意义的,因为post 可能会被其他persons 引用)。

但是从你的名字(PersonPost)猜测,我认为你可能可以使用 Person has_many :postsPost belongs_to :person,在这种情况下,你可以在 @987654333 上使用 :dependent =&gt; :destroy @关联。

【讨论】:

  • 能否请您添加如何在 双向 has_and_belongs_to_many 关系上实现 dependent: :destroy 操作,该关系链接到 同一模型 ?
  • 我不确定语法最初是否像这个答案,但我知道在 rails 4 中它应该是 before_destroy { posts.clear }
  • 我发现我不需要在 rails 4.2.0 (postgresql) 中做before_destroy { posts.clear }。 Rails默认删除关系(不删除相关记录,本例中post)。
  • 不错的小费信仰。 has_and_belongs_to_many 继续删除 rails 5.0.0beta2 中的关联
  • @Fatih 评论需要作为答案!
【解决方案2】:

是的,它不支持它。 See the docs。通常habtm 仅适用于非常非常简单的情况,如果您开始需要更复杂的事情,您应该切换到has_many :through

【讨论】:

    【解决方案3】:

    试试这个:

    class Person < ActiveRecord::Base
      has_and_belongs_to_many :posts
      before_destroy do
        posts.each { |post| post.destroy }
      end
    end
    

    您不需要 post.clear,因为 Rails 4.2+ 已经处理了这个问题。

    【讨论】:

    • 这是正确答案。 Rails 4.2+ 和 5+ 都会在您销毁 HABTM 关联后立即销毁关联表。
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2021-10-25
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多