Is it possible to invert a named scope in Rails3?

假装没事ソ 提交于 2019-12-05 18:02:41

问题


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?


回答1:


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



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!