从现有的ActiveRecord :: Relation获取一个空白的新关系

时间:2015-02-08 07:32:15

标签: ruby-on-rails ruby activerecord

在我的项目中,我使用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 ...语句的新关系?

1 个答案:

答案 0 :(得分:0)

不太确定你在做什么,但听起来你正在寻找unscoped方法:

Product.unscoped.where(id: product_ids)