Reputation: 142
In my rails application, I have relationship setup such has
user has_many :contacts
, all the contacts of a user are stored in contacts
when I do user.contacts
i get all the contacts of a current_user
I wanted to check how many of the user contacts are already registered meaning already existing in users table. I have some solution in mind my comparing of each contact of a user with the db(users table). But the process will very time consuming looking for a more optimized way.
Upvotes: 0
Views: 86
Reputation: 2520
Assuming your Contact
model has email
as an attribute and User
also has email
as an attribute. To find the number of users that are registered with the emails that are as contacts of current_user
, you would do:
contact_emails = current_user.contacts.pluck("contacts.email")
no_of_users_registered = User.where(email: contact_emails).count
Upvotes: 1
Reputation: 7561
You could use an association extension to do this:
class User
has_many :contacts do
def persisted
where(email: User.select(:email))
end
end
end
Assuming both your contact and user models have an email field.
Upvotes: 0