3

以下に示すように、belongs_to - has_many 関係を持つ 2 つのモデルがあります (モデルが非常に大きいため、この質問に関連するコードの部分のみを含めました)。

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 の Readme ( 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 productsWHERE products. id= 1 LIMIT 1」が実行され、実行時エラーが発生します:「RuntimeError: TestCycle#product_title delegated to product.title,しかし製品はゼロです。」

ただし、データベースで直接クエリを実行すると、製品が見つかります (実際には削除されておらず、acts_as_paranoid によって設定された deleted_at フィールドしかないため)。

そのため、製品モデルの「with_deleted: true」は無視されているようです。なぜこれが起こっているのですか?それとも、これが機能しない理由が他にあるのでしょうか?

私は自分自身を明確にすることを願っています. そうでない場合は、お問い合わせください. ありがとう!

4

1 に答える 1