0

从字面上看,我刚开始学习 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")},但没有使查询有所不同。

提前致谢!

4

1 回答 1

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 }) }
于 2018-06-15T13:06:31.460 回答