Unscope 特定 where 值

Unscope specific where values

我有很多标签的产品模型

class Product < ApplicationRecord
  has_and_belongs_to_many :tags
end

我将多个 where 条件应用于产品范围

@products = Product.includes(:tags).where(tags: { id: [1] })
@products = @products.where(tags: { id: [2] })

稍后在代码中我需要取消范围@products 关系。但只是特定的条件组,而不是整个where子句。

@products = @products.somehow_i_dont_know_how_unscope(tags: { id: [2] })

assert_eqal Product.includes(:tags).where(tags: { id: [1] }), @products

根据业务逻辑,我无法在实际应用 where 条件之前进行此检查。以后有什么办法可以恢复这种情况吗?

我的想法是,我们从 where_clauserewhereunscope 中删除特定的 where 也是这样做的。

@products = Product.includes(:tags).where(tags: { id: [1] })
@products = @products.where(tags: { id: [2] })

@products.where_clause -= Product.where(tags: { id: [2] }).where_clause

assert_equal Product.includes(:tags).where(tags: { id: [1] }), @products # ok