【问题标题】:Dependent: :destroy only to the 2nd degree in has many through associationDependent: :destroy only to 2nd degree in has many through association
【发布时间】:2018-05-23 07:44:18
【问题描述】:

我有三个模型。一个collection 有许多searchesitems。 当 collection 被销毁时,我希望它的 items 被销毁,但 searches 被取消,因为它们本身仍然是有效的对象。 这个可以吗?

这是我的模型:

class Collection < ApplicationRecord
  has_many :searches, through: :items
  has_many :items
  has_many :searches, through: :suggestions
  has_many :suggestions
end

class Item < ApplicationRecord
  belongs_to :collection
  belongs_to :search
end

class Search < ApplicationRecord
  has_many :collections, through: :items
  has_many :items
  has_many :collections, through: :suggestions
  has_many :suggestions
end

【问题讨论】:

  • 你可以写一个方法来做到这一点。会是明确的
  • 谢谢!我确信有办法在has_many :items 上调用dependent: destroy 和在has_many :searches, through :items 上调用dependent :nullify,但我想没有?
  • 顺便说一句,您需要重命名has_many :searches 之一。模型不能有两个具有相同名称的不同关联

标签: ruby-on-rails activerecord rails-activerecord polymorphic-associations


【解决方案1】:

可以删除项目,只需将dependent: :destroy 添加到has_many :items

class Collection < ApplicationRecord
  has_many :searches, through: :items
  has_many :items, dependent: :destroy
end

销毁集合后,项目被销毁,但搜索将保留。

第二种解决方案

您甚至可以将dependent: :nullify 应用于has_many :searches - 得到相同的结果。

class Collection < ApplicationRecord
  has_many :searches, through: :items, dependent: :nullify
  has_many :items
end

来自the docs

collection.delete(object, ...)

通过将外键设置为NULL,从集合中删除一个或多个对象。如果对象与dependent: :destroy 关联,则它们将被另外销毁,如果它们与dependent: :delete_all 关联,则将被删除。

如果使用:through 选项,则默认情况下会删除(而不是无效)连接记录,但您可以指定dependent: :destroydependent: :nullify 来覆盖它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 2011-02-08
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多