我在学习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")}
,但没有使查询有所不同。
提前致谢!
答案 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 }) }