Jesper Rønn-Jensen
Jesper Rønn-Jensen

Reputation: 111696

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?

Upvotes: 10

Views: 2488

Answers (2)

Tobias
Tobias

Reputation: 1938

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)"

Upvotes: 10

fl00r
fl00r

Reputation: 83680

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("<=")

Upvotes: 1

Related Questions