在我的项目中,我使用closure_tree
gem并希望在我的Product
模型上编写自定义方法,该方法返回给定集合的所有父项。
我试着写类方法:
class Product < ActiveRecord::Base
has_closure_tree
def self.tree_parents
root_product_ids = []
all.each do |product|
root_product_ids << (product.root? ? product.id : product.parent_id)
end
Product.where(id: root_product_ids)
end
end
返回的关系正在与前一个合并,但是我需要这个方法来返回绝对新的独立ActiveRecord::Relation
:
» leaf_product = Product.where(id: 219)
Product Load (0.7ms) SELECT "products".* FROM "products" WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219
=> #<ActiveRecord::Relation [#<Product id: 219, name: ... ]>
» leaf_product.tree_parents
Product Load (1.0ms) SELECT "products".* FROM "products" WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219
Product Load (0.7ms) SELECT "products".* FROM "products" WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219 AND "products"."id" IN (1)
=> #<ActiveRecord::Relation []>
简而言之,我希望此方法仅返回Product.where(id: root_product_ids)
,不要将其与Product.where(id: 219)
链接。
如何在没有父关系IN
声明的情况下返回仅包含WHERE id ...
语句的新关系?