简体   繁体   中英

Comparing one array against another in rails

I am using the 'contacts' gem in rails to retrieve a users contacts from their mail application. It returns the contacts like so:

["person name", "personemail@example.com"], ["person name", "personemail@example.com"], ["person name", "personemail@example.com"] etc...

I want to compare this list to the Users already signed up for my site

Users.find(:all) returns:

[#<User id: 11, login: "examplelogin", email: "example@example.com">, #<User id: 12, login: "examplelogin", email: "example@example.com">, etc... ]

What is the best way to go about comparing the gmail contact emails to the User emails and displaying only the ones that are a match?

I was thinking something like:

@contacts = Contacts::Gmail[params[:from]].new(params[:login], params[:password]).contacts
@contacts.each do |c|
  @email = c[1]
  @user = Users.find_by_email(@email)
end

Which would presumably only return the users where there was a match. I feel like there must be a better way to go about this that I am not considering. Any suggestions?

@users = Users.find_all_by_email(@contacts.collect{|contact| contact[1]})

edit:

What you had before would perform a find for each contact and leave you only with the result of the last query, either a user or not depending on whether one existed with this email. This performs one query and returns an array of all successful matches:

where 'users'.'email' in array_of_email_addresses. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM