Reputation: 988
I need to give 2 filter conditions in the scope clause of a model class in my Ruby on Rails code.
I tried this:
scope :post_total, -> {where(division: 'PMT', 'key between ? and ?, 3, 7)}
division and key are the 2 column names on which I need to the filtering.
So, I need to implement this condition basically:
WHERE DIVISION = 'PMT' AND KEY BETWEEN 3 AND 7
I am getting an error in my Rails scope condition shown above. What is the correct way to write this scope condition?
Please help!
Upvotes: 1
Views: 690
Reputation: 5061
I would go with this:
scope :post_total, -> { where division: 'PMT', key: 3..7 }
Upvotes: 1
Reputation: 33542
This should do
scope :post_total, -> {where("division = ? AND key BETWEEN ? AND ?", 'PMT', 3,7)}
Upvotes: 1
Reputation: 12203
You can chain where
clauses to use Rails syntax and straight SQL:
scope :post_total, -> { where(division: 'PMT').where('key BETWEEN ? AND ?', 3, 7) }
Rails will execute this as one query, structured in the desired manner.
Hope that helps - let me know if you've any questions.
Upvotes: 1