Vibhoo Mishra Vibhoo Mishra - 4 months ago 19
Ruby Question

how do I check whether user exists in db or not

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.

Answer

Assuming your Contact model has email as an attribute and User also have email as a field. 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
Comments