Is it possible to invert a named scope in Rails3?

2020-07-06 03:50发布

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?

2条回答
不美不萌又怎样
2楼-- · 2020-07-06 04:17

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("<=")
查看更多
做自己的国王
3楼-- · 2020-07-06 04:19

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)"
查看更多
登录 后发表回答