ActiveRecord检查单个查询中是否存在多个记录

时间:2013-12-29 09:07:58

标签: ruby-on-rails activerecord

def joined
  contacts = params[:contacts] || []

  contacts.keep_if do |contact|
    User.exists?(phone: contact)
  end

  render :json => {contacts: contacts}
end

如果有数据库中有指定联系人的用户,我正在尝试根据条件对联系人数组进行子集化。上面代码的问题是我为数组中的每个联系人命中了数据库。有没有办法用ActiveRecord一次性完成这个?

编辑1:修正了拼写错误, 编辑2:更好的解释

2 个答案:

答案 0 :(得分:1)

在我看来,从一个数字列表中,您只想选择user.phone在数字列表中的数字:

params[:contacts]  = ['2345435', '5675678', '898785']

def joined
  numbers = params[:contacts] || []
  contacts = User.where(phone: numbers).pluck(:phone)
  render :json => {contacts: contacts}
end

这将仅返回通过电话号码在db中找到的用户的联系人(电话号码)。

电子邮件示例(在您的情况下是电话):

1.8 :002 > emails = ['admin2002@gmail.com', 'admin2002@yahoo.com', 'admin2002@hotmail.com']
1.8 :007 > contacts = User.where(:email => emails).pluck(:email)
   (1.3ms)  SELECT email FROM `users` WHERE `users`.`is_company` = 0 AND `users` .`email` IN ('admin2002@gmail.com', 'admin2002@yahoo.com', 'admin2002@hotmail.com')
 => ["admin2002@gmail.com", "admin2002@yahoo.com"]

答案 1 :(得分:0)

def joined
  contacts = params[:contacts] || []

  db_contacts = User.where(:phone=> contacts.map(&:contact)).select(:phone) #=> returns all the existing users phone num

  # This is not required if your intention is only to have contacts that exists in db
  contacts.keep_if{ |contact| db_contacts.include?(contact) }

  render :json => {contacts: db_contacts}
end