如何在命名范围内拥有多个条件?

我有一个用户模型。 我可以通过执行a_user.try(:admin?)来检查用户是否是管理员。

我想定义一个命名范围,它可以在最后X分钟内更新所有用户,而不是管理员。 到目前为止我有:

 scope :recent, lambda { { :conditions => ['updated_at > ?', 5.minutes.ago] } } 

这成功地使所有用户在最近5分钟内更新,但如何合并管理员检查? 我不知道如何在范围内的用户实例上调用try()

如果users表中的admin列是布尔值,

 scope :recent, lambda { :conditions => ['updated_at > ? AND admin != ?', 5.minutes.ago, true] } 

另一种可能性,可用于Rails 4,

 scope :recent, -> { where('updated_at > ?', 5.minutes.ago } # If you were using rolify, you could do this scope :non_admin, -> { without_role :admin } # given the OP question, scope :non_admin, -> { where(admin: false) } scope :non_admin_recent, -> { non_admin.recent } 

这只是另一种可能的格式,并考虑到使用Rolify gem的可能性。

我发现使用类方法更干净,而不是使用lambda

 def self.recent where('updated_at > ?', 5.minutes.ago) end def self.admin where(admin: true) end def self.recent_and_admin recent.admin # or where('updated_at > ?', 5.minutes.ago).where(admin: true) end