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?
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)"
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("<=")
来源:https://stackoverflow.com/questions/9574959/is-it-possible-to-invert-a-named-scope-in-rails3