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

Xåp*_* - 6 scope named-scope model ruby-on-rails rails-models

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

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

scope :recent, lambda { { :conditions => ['updated_at > ?', 5.minutes.ago] } }
Run Code Online (Sandbox Code Playgroud)

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

rpb*_*zar 12

另一种可能性,可用于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 }
Run Code Online (Sandbox Code Playgroud)

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


shw*_*eta 7

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

scope :recent, lambda { :conditions => ['updated_at > ? AND admin != ?', 5.minutes.ago, true] }
Run Code Online (Sandbox Code Playgroud)


jvn*_*ill 6

而不是使用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
Run Code Online (Sandbox Code Playgroud)