Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ruby on rails - How to have multiple conditions in a named scope?

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...