How to have multiple conditions in a named scope?

十年热恋 提交于 2019-11-29 11:06:05

if admin column in users table is a boolean,

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

Just another possibility, usable in 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 }

This is just another possible format and taking in account the possibility of using Rolify gem.

Instead of using lambda, I find it cleaner to use class methods.

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