Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord. Find all records by attribute the values of which are included in array

I need to create a scope on my User model that would get all the users whose email attribute is included into the AdminUser model's emails.

Basically, there's an attribute called email in the User model and the same attribute in the AdminUser model. So, I need to get all the users which are actually admins (by emails).

I didn't succeed in implementing this as a signle query and started with getting the array of AdminUser emails:

emails = AdminUser.pluck(:email)

and now I'm struggling with getting the array of admin users from User model.

If I write something like this:

User.find_by_email(emails)

I get just one entity, not the array.


So, my question:

How can I create a scope, say admins, on the User model that would return the array of admins?


BTW: for some other purposes I have this method in my User:

  def admin?
    AdminUser.find_by(email: email) ? true : false
  end

so, maybe I could somehow make use of it in this case?

like image 315
Denis Yakovenko Avatar asked Aug 31 '15 10:08

Denis Yakovenko


1 Answers

If you pass an array to the value of an attribute in a where clause, it'll do what you want.

@user = User.where(email: AdminUser.pluck(:email))
like image 156
SteveTurczyn Avatar answered Apr 29 '23 12:04

SteveTurczyn