Deutro
Deutro

Reputation: 3323

How can I get all models which have their field in a list?

I have a user model in my rails application which has a phone number field. On an Android phone I want to get all of his contacts phone numbers and search my users for these phone numbers. For example:

user phoneNumber
1    0111/11111111
2    0222/22222222
3    0333/33333333

This are the users in my data base. The list I get in Android might have 2 phone numbers:

0111/11111111, 0222/22222222, 0444/44444444

How can I get the users with matching phone numbers from my database the most efficient way?

Upvotes: 0

Views: 47

Answers (1)

Anand
Anand

Reputation: 3760

Assuming that:

  • You are in the rails app, and have imported the android contacts
  • You have an android_contacts array where each contact has a phone_number
  • You have a User model with the phone_number field,
  • The phone numbers in both places are formatted identically

the following ruby code should work:

@matching_users = []
(android_contacts.map(&:phone_number) & User.map(&:phone_number)).each do |phone_number|
  @matching_users << User.find_by! phone_number: phone_number
end
# @matching_users now contains the required users

Upvotes: 1

Related Questions