我有两个具有belongs_to - has_many 关系的模型,您可以在下面看到(我只包含了与这个问题相关的代码部分,因为模型很大):
product.rb
class Product < ActiveRecord::Base
attr_accessible :title, :description, [...]
has_many :test_cycles
acts_as_paranoid
end
test_cycle.rb
class TestCycle < ActiveRecord::Base
belongs_to :product, with_deleted: true
acts_as_paranoid
delegate :title, to: :product, prefix: true
end
根据 Github 上的自述文件(https://github.com/goncalossilva/acts_as_paranoid),这应该有效:
class Parent < ActiveRecord::Base
has_many :children, :class_name => "ParanoiacChild"
end
class ParanoiacChild < ActiveRecord::Base
belongs_to :parent
belongs_to :parent_including_deleted, :class_name => "Parent", :with_deleted => true
# You cannot name association *_with_deleted
end
parent = Parent.first
child = parent.children.create
parent.destroy
child.parent #=> nil
child.parent_including_deleted #=> Parent (it works!)
但是,如果我删除测试周期的父产品并尝试通过 test_cycle.product 访问它(假设 test_cycle 和 product 对象都存在),它会返回 nil(即使模型中包含 with_deleted: true !) .
如果我在与已删除产品相同的 test_cycle 上调用 test_cycle.product_title,它会运行查询“SELECT products
.* FROM products
WHERE products
. id
= 1 LIMIT 1”并且我收到运行时错误:“RuntimeError: TestCycle#product_title delegated to product.title,但产品为零”。
但是,如果我直接在数据库中运行查询,则会找到产品(因为它并没有真正被删除,而只有一个由acts_as_paranoid 设置的 deleted_at 字段)。
因此,似乎忽略了产品模型中的“with_deleted:true”。知道为什么会这样吗?或者还有其他原因导致这不起作用吗?
我希望我能说清楚,如果没有,请询问,我很乐意提供更多信息。谢谢!