0

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

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

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

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

这是我的三个模型

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

我不是红宝石最好的,所以如果您有任何建议,请随时分享。先感谢您

4

1 回答 1

0

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

  def resource
    Resource.unscoped {super}
  end

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

Resource.unscoped {super}

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

于 2018-12-04T17:15:48.090 回答