【问题标题】:Soft-deleted object from parent model not accessible in my child model在我的子模型中无法访问父模型中的软删除对象
【发布时间】:2018-12-04 14:34:16
【问题描述】:

允许我的用户删除他自己创建的一些资源,但是当他销毁资源时,出现问题,因为我有一个名为 resourcequantity 的模型,它依赖于资源模型,我不想创建一个依赖销毁,因为它会影响我的用户已经创建的工作组(工作组是一个包含多个资源的模型,通过 resource_quantities 见下文)。

我正在尝试做的是允许我的用户软删除其资源,同时将资源保留在数据库中以保持所有文档不变,即使某些资源已被破坏。

我目前正在使用 paranoia gem,并尝试实现dependent: :nullify,但没有取得很大成功。使用 paranoia gem 时,我得到了 nill 类的 NoMethodError,因为它只会查找 deleted_at 为 null 的资源。

我有点迷茫,不知道从哪里开始。

这是我的三个模型

class Resource < ApplicationRecord
acts_as_paranoid

  has_many :workgroups, through: :resource_quantities
  has_many :resource_quantities, inverse_of: :resource, dependent: :nullify
  accepts_nested_attributes_for :resource_quantities, allow_destroy: true
end

class ResourceQuantity < ApplicationRecord

  belongs_to :workgroup, optional: true, inverse_of: :resource_quantities
  belongs_to :resource, optional: true, inverse_of: :resource_quantities
  accepts_nested_attributes_for :resource, :allow_destroy => true

  validates :workgroup, uniqueness: { scope: :resource }
end

 class Workgroup < ApplicationRecord
     acts_as_paranoid

   has_many :resource_quantities, inverse_of: :workgroup, dependent: :destroy
   has_many :resources,  through: :resource_quantities, dependent: :nullify


   accepts_nested_attributes_for :resource_quantities, allow_destroy: true
   belongs_to :contractor

   belongs_to :workgroup_library, optional: true
   validates :name, presence: true
 end

是否可以在资源被软删除的情况下做这样的事情?

def total_cost_price
     total_cost_price = 0
     self.resource_quantities.each do |f|
       total_cost_price += f.resource.purchase_price
     end
     total_cost_price.round(2)
  end

我在 ruby​​ 方面不是最好的,所以如果您有任何建议,请随时分享。提前谢谢你

【问题讨论】:

  • 您可以使用with_deleted 范围来查看所有关联,但是如果您取消了关系,那也没关系,因为关系现在完全断开了。
  • 是的,你确实是对的:p 我正在调查这个方向相同的问题:github.com/rubysherpas/paranoia/issues/176

标签: ruby-on-rails ruby nested-forms ruby-paranoia


【解决方案1】:

好的,此问题已通过在属于 Resource 模型的模型中定义资源来解决。

  def resource
    Resource.unscoped {super}
  end

由于偏执狂,我可以从其他模型访问我的资源,即使它们已从资源模型中删除。 (无需取消关系)

Resource.unscoped {super}

它实际上删除了您可以在控制台中观察到的“WHERE ("resources"."deleted_at" NULL)”,这非常方便。

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2018-06-24
    • 2020-01-06
    相关资源
    最近更新 更多