Vibhoo Mishra Vibhoo Mishra - 1 year ago 77
Ruby Question

how do I check whether user exists in db or not

In my rails application, I have relationship setup such has

has_many :contacts
, all the contacts of a user are stored in contacts

when I do
i get all the contacts of a
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 Source

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("")
no_of_users_registered = User.where(email: contact_emails).count
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download