Is it possible to invert a named scope in Rails3?
Asked Answered
F

2

10

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?

Fendley answered 5/3, 2012 at 22:22 Comment(0)
D
10

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)"
Dentilingual answered 6/3, 2012 at 8:47 Comment(1)
Clever! Although your answer suggests i cannot define the first and then just "not" the first scope like so: scope :above_limit, within_limit.notRiyal
U
1

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("<=")
Unbeliever answered 5/3, 2012 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.