0
votes

I'm literally just a few days old from learning Rails and I'm currently working on queries using scopes.

I have this simplified code:

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

Firing up rails c and typing in Product.get_items it instead produces:

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

when I needed:

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

Did some research and also tried {where("producer_id IS NOT NULL")} but doesn't make the query different.

Thanks in advance!

1
Product.where.not(producer_id: nil) does it work? - Ravi Mariya
Try this scope :get_items, (lambda do where.not(producer_id: nil) end) - Rohit Lingayat

1 Answers

0
votes

scope: where.not(producer{id: nil} shouldn't work at all. Instead:

# 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 }) }