Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to invert a named scope in Rails3?

In my Rails3 model I have these two named scopes:

scope :within_limit,     where("wait_days_preliminary <= ? ", ::WAIT_TIME_LIMIT.to_i )
scope :above_limit,      where("wait_days_preliminary > ? ",  ::WAIT_TIME_LIMIT.to_i )

Based on their similarity, it would be natural for me to define the second by inverting the first.

How can i do that in Rails?

like image 226
Jesper Rønn-Jensen Avatar asked Mar 05 '12 22:03

Jesper Rønn-Jensen


2 Answers

Arel has a not method you could use:

condition = arel_table[:wait_days_preliminary].lteq(::WAIT_TIME_LIMIT.to_i)
scope :within_limit, where(condition)     # => "wait_days_preliminary <= x"
scope :above_limit,  where(condition.not) # => "NOT(wait_days_preliminary <= x)"
like image 145
Tobias Avatar answered Feb 05 '23 11:02

Tobias


I believe this could work

scope :with_limit, lambda{ |sign| where("wait_days_preliminary #{sign} ? ", ::WAIT_TIME_LIMIT.to_i ) }

MyModel.with_limit(">")
MyModel.with_limit("<")
MyModel.with_limit(">=")
MyModel.with_limit("<=")
like image 41
fl00r Avatar answered Feb 05 '23 11:02

fl00r