Rails 4.2 范围查询 IS NULL 而不是 IS NOT NULL

Rails 4.2 Scope queries IS NULL instead of IS NOT NULL

我刚学 Rails 几天,目前正在使用作用域进行查询。

我有这个简化的代码:

Class Product  < ActiveRecord::Base
   belongs_to: producer
   scope: get_items, => {where.not(producer{id: nil})}

启动 rails c 并输入 Product.get_items 它会生成:

SELECT "products".* FROM "products" WHERE (producer_id IS NULL)

当我需要时:

SELECT "products".* FROM "products" WHERE (producer_id IS NOT NULL)

做了一些研究,也尝试了 {where("producer_id IS NOT NULL")},但没有使查询不同。

提前致谢!

scope: where.not(producer{id: nil} 根本不起作用。相反:

# if you need to filter by the attribute of the current model
scope :with_producer, -> { where.not(producer_id: nil) }

# if you need to filter by the attribute of the associated model
scope :with_named_producer, -> { joins(:producer).where.not(producers: { name: nil }) }