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

时间:2018-06-15 09:35:14

标签: ruby-on-rails postgresql ruby-on-rails-4.2

我在学习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")},但没有使查询有所不同。

提前致谢!

1 个答案:

答案 0 :(得分:0)

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 }) }
相关问题