【问题标题】:Unscope specific where values取消特定范围的值
【发布时间】:2021-06-10 14:58:46
【问题描述】:

我有很多标签的产品模型

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 条件之前进行此检查。以后有什么办法可以恢复这种情况吗?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    我的想法是我们从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
    

    【讨论】:

    • @Lam Phan 我知道了。它有效,但前提是 -= 的范围参数与原始数组完全匹配。 [2,9999] - 这被跳过而不是只删除“2”子句
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    相关资源
    最近更新 更多