How to have multiple conditions in a named scope?

I have a User model. I can check if the user is an administrator by running a_user.try(:admin?).

I would like to define a named area in which all users are updated in the last X minutes that are not admins. So far I:

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

This successfully updates all users in the last 5 minutes, but how do I enable administrator verification? I do not know how to call try()in a user instance inside a scope ...

+5
source share
3 answers

if the admin column in the users table is logical,

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

Another feature that you can use 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 }

Rolify.

+12

Instead of using it, lambdaI 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
+6
source

All Articles