How to have multiple conditions in a named scope?

后端 未结 3 1651
南方客
南方客 2020-12-18 04:58

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

相关标签:
3条回答
  • 2020-12-18 05:35

    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.

    0 讨论(0)
  • 2020-12-18 05:36

    if admin column in users table is a boolean,

    scope :recent, lambda { :conditions => ['updated_at > ? AND admin != ?', 5.minutes.ago, true] }
    
    0 讨论(0)
  • 2020-12-18 06:01

    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
    
    0 讨论(0)
提交回复
热议问题