user2129376
user2129376

Reputation: 33

Rails SQL Query if null

I'm trying to do a rails scope using a lambda function by passing in one value:

"scope :for_rank, lambda {|rank| where('min_rank <= ? AND max_rank >= ?', rank, rank)}"

however, it is possible that max_rank is null. In this situation, I want the query to only do the min_rank <= ? part. How can I do this?

Example:

"a.min_rank = 10"
"a.max_rank = 20"
"b.min_rank = 15"
"b.max_rank = nil"

i want the search of for_rank(15) should return both a and b.

Upvotes: 2

Views: 817

Answers (1)

Rahul Tapali
Rahul Tapali

Reputation: 10137

Try this:

 scope :for_rank, lambda {|rank| where('(min_rank <= ? AND max_rank IS NOT NULL AND max_rank >= ?) OR (min_rank <= ? AND max_rank IS NULL)', rank, rank, rank)}

Upvotes: 2

Related Questions