gpt4 book ai didi

ruby-on-rails - Rails act_as_paranoid-belongs_to 不使用 with_deleted

转载 作者:行者123 更新时间:2023-12-04 18:08:29 28 4
gpt4 key购买 nike

我有两个模型与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 和产品对象),它将返回 nil(即使 with_deleted: true 包含在模型中!) .

如果我使用删除的产品在同一个 test_cycle 上调用 test_cycle.product_title,它会运行查询“SELECT products .* FROM products WHERE products . id = 1 LIMIT 1”,我得到一个运行时错误:
“运行时错误:TestCycle#product_title 委托(delegate)给 product.title,但产品为零”。

但是,如果我直接在数据库中运行查询,就会找到产品(因为它并没有真正被删除,而只有一个由acts_as_paranoid 设置的deleted_at 字段)。

因此似乎忽略了产品模型中的“with_deleted: true”。知道为什么会这样吗?或者还有其他原因导致这不起作用吗?

我希望我说清楚,如果没有,请询​​问,我很乐意提供更多信息。谢谢!

最佳答案

您还必须提供外键 .如果您查看规范,则很明显,但文档不是最新的。

使用此代码:

class ParanoiacChild < ActiveRecord::Base
belongs_to :parent
belongs_to :parent_including_deleted, :class_name => "Parent", :foreign_key => "parent_id", :with_deleted => true
# You cannot name association *_with_deleted
end

这是规范中的片段(参见: https://github.com/goncalossilva/acts_as_paranoid/blob/rails3.2/test/test_helper.rb):
class ParanoidHasManyDependant < ActiveRecord::Base
acts_as_paranoid
belongs_to :paranoid_time
belongs_to :paranoid_time_with_deleted, :class_name => 'ParanoidTime', :foreign_key => :paranoid_time_id, :with_deleted => true
belongs_to :paranoid_time_polymorphic_with_deleted, :class_name => 'ParanoidTime', :foreign_key => :paranoid_time_id, :polymorphic => true, :with_deleted => true

belongs_to :paranoid_belongs_dependant, :dependent => :destroy
end

关于ruby-on-rails - Rails act_as_paranoid-belongs_to 不使用 with_deleted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20355018/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com