【问题标题】:Rails 4.2 dependent: :destroy problems with CollectionProxyRails 4.2 依赖: :destroy 与 CollectionProxy 的问题
【发布时间】:2015-03-01 21:46:45
【问题描述】:

我之前在模型上使用过dependent: :destroy 没有任何问题,但在 Rails 4.2 中我被卡住了。过去的用途主要是经典的 has_many belongs_to 模型。似乎#<ActiveRecord::Associations::CollectionProxy 引起了我的问题。

楷模
    class Subject < ActiveRecord::Base
        has_many :properties
        has_many :values, :through => :properties
        has_many :tags, :through => :properties

    class Property < ActiveRecord::Base
      belongs_to :subject
      belongs_to :tag
      belongs_to :value

    class Value < ActiveRecord::Base
        has_one :property
        has_one :subject, :through => :property
        has_one :tag, :through => :property

    class Tag < ActiveRecord::Base
        has_many :properties
        has_many :subjects, :through => :properties

我的目标是

  • 删除主题将删除所有关联的属性和值
  • 删除属性将删除关联的值,使主题保持不变
  • 或者,删除一个值将删除关联的属性,保持主题不变

我尝试在主题中的值行和值中的属性行上添加依赖破坏。它会删除属性,但不会删除值。我尝试将它放在属性中的值属性行和值行并得到相同的结果 - 它不会删除值。

然后我尝试before_destroy 过滤器并在尝试模型关联时遇到了相同类型的问题或ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR。然后我破解了它并让它工作:

    # In Subject model
    before_destroy :destroy_values
    def destroy_values
        # relations does not seem to work got the Values using a new query
            #values.destroy_all
        pids = values.pluck(:id)
        Value.where(id:pids).destroy_all
    end

    # in Value model
    before_destroy :destroy_property
    def destroy_property
        property.destroy 
    end

不知道发生了什么,尽可能多地阅读 dependent 并尝试 delete_all,以及我看到的所有其他事情,我不高兴!

是的,这是一个奇怪的模型,只是玩弄并试图复制“Whatit?” Rails 中的 Apple II 数据库,让您大开眼界。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    有时,当您陷入困境时,您只需要问一个问题。当你没有得到答案时,你就有时间重新考虑这个问题。我想我没有尝试所有选项。

    我认为问题在于我不理解无效的默认策略。根据我的目标,没有属性就没有价值,反之亦然。尝试使用直通关联进行销毁会引发 pg 错误。我显然没有尝试过的简单解决方案是依赖破坏主题模型中的属性和依赖破坏属性模型中的值。指南中关于不要对belongs_to 关联使用依赖销毁的警告可能已经开始了我的循环之旅。我仍然不确定我是否理解警告。我的猜测是当subject.properties被销毁时,在调用property.valuedestroy之前将subject_id设置为null,避免了pg错误。我清理过的模型:

        class Subject < ActiveRecord::Base
            has_many :properties, dependent: :destroy
            has_many :values, :through => :properties
            has_many :tags, :through => :properties
    
        class Property < ActiveRecord::Base
          belongs_to :subject
          belongs_to :tag
          belongs_to :value, dependent: :destroy
    
        class Value < ActiveRecord::Base
            has_one :property
            has_one :subject, :through => :property
            has_one :tag, :through => :property
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多