我如何"unscope";查询但保持has_many
关系?
我有两个模型。它们每个都有default_scopes
,我也用不同的scopes
(visibility
、active
等(进行查询
class Shop
has_many :products
scope :active, -> { where(active: true, visible: true) }
end
class Product
belongs_to :shop
default_scope { where(:visible => true, active: true) }
end
active_shop = Shop.create(name: "active",
active: true,
visible: true)
inactive_shop = Shop.create(name: "inactive",
active: false,
visible: false)
active_shop.products.create!(name "active product",
visible: true,
active: true)
inactive_shop.products.create!(name "inactive product",
visible: false,
active: false)
有时我需要更改特定商店的所有相关产品的值。我必须";unscope";克服CCD_ 6的产品:但我当时的问题是,这也删除了has_many
查询:
inactive_shop.products.unscoped.map(&:name)
# ["inactive product","active product"]
但我只希望返回"inactive product"
提示:这是一个简化的例子。所以一个简单的
scope :visible, -> { where(visible: true) }
scope :active, -> { where(active: true) }
不可能,因为在我的真实代码中作用域更复杂。
我需要的是这样的东西:Shop.products.all_products_of_this_shop_equally_which_scope
使用unscoped
,我还可以获得整个应用程序的所有产品。Unscope
还添加了另一个Shop
:的Products
>> Shop.last.products.to_sql
Shop Load (1.9ms)
SELECT "shops".* FROM "shops"
ORDER BY "shops"."id"
DESC LIMIT $1 [["LIMIT", 1]]
=> "SELECT "products".* FROM "products"
WHERE "products"."visible" = TRUE
AND "products"."active" = TRUE
AND "products"."shop_id" = 234"
>> Shop.last.products.unscoped.to_sql
Shop Load (2.7ms)
SELECT "shops".* FROM "shops"
ORDER BY "shops"."id"
DESC LIMIT $1 [["LIMIT", 1]]
=> "SELECT "products".* FROM "products""
# BUT I NEED THIS:
"SELECT "products".* FROM "products"
WHERE "products"."shop_id" = 234"
在产品查询中,我需要保留与商店的关系,但删除所有其他查询
提前非常感谢
我认为您可以尝试使用unscope
而不是unscoped
。它允许指定需要取消范围(ref(的特定方法,如以下所示:
inactive_shop.products.unscope(where: %i[active visible]).map(&:name)
或者,如果默认范围中有许多WHERE条件,并且您想取消对除shop_id之外的所有WHERE条件的范围,则可以尝试以下操作:
inactive_shop.products.unscope(
where: inactive_shop.products.where_values_hash.except('shop_id').keys
).map(&:name)
然而,在这一点上,我会考虑取消默认范围。。。