6

I have a User model. I can check whether a User is an admin by doing a_user.try(:admin?).

I'd like to define a named scope that gets all Users updated within the last X minutes who are not admins. So far I have:

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

This successfully gets all Users updated within the last 5 minutes, but how do I incorporate the admin check? I don't know how to call try() on an instance of a User inside the scope...

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
  • I think this question is partially answered here: [http://stackoverflow.com/questions/2352860/rails-named-scopes-conditional-conditions][1] [1]: http://stackoverflow.com/questions/2352860/rails-named-scopes-conditional-conditions – mimsugara Jan 31 '13 at 10:55

3 Answers3

15

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.

rpbaltazar
  • 801
  • 7
  • 15
9

if admin column in users table is a boolean,

scope :recent, lambda { :conditions => ['updated_at > ? AND admin != ?', 5.minutes.ago, true] }
shweta
  • 8,019
  • 1
  • 40
  • 43
  • Thanks. But I had to change `&&` to `AND` because it was giving me syntax errors. I also used `true` instead of `1`, just because it's more readable. – XåpplI'-I0llwlg'I - Jan 31 '13 at 11:21
6

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
jvnill
  • 29,479
  • 4
  • 83
  • 86