使用Ruby在两个表之间进行查询

时间:2013-05-18 06:32:15

标签: mysql ruby-on-rails

我的代码就是这个

contact = UserContact.find(:all,:select=>"distinct app_id,number",:conditions=>"number ='1234'")

arr=[]
contact.each do|c|
 arr << c.app_id
end
name=User.find(:all,:conditions=>"id in(#{arr.join(',')}")

我花了两倍的时间我可以使用join

这样做

由于

2 个答案:

答案 0 :(得分:0)

你应该像这样做

User.find(:all, :joins => :user_contacts, :conditions => "user_contacts.number = '1234'")

用户应该有关联。在user.rb中应该是:

has_many :user_contacts, :foreign_key => :app_id

但是将列“app_id”命名为“user_id”(约定优于配置)是不好的方式。重命名它。重命名后,您可以删除“,:foreign_key =&gt;:app_id”

答案 1 :(得分:0)

很遗憾,您无法在同一个Active记录查询中执行“包含”和“选择”。所以这不会起作用......

contacts = UserContact.includes(:users).where("number = ?", '1234').select(:app_id, :number).uniq

BUT。

FIRST:app_id看起来应该被称为“user_id”

SECOND:您使用的是什么版本的Rails?如果使用rails 3.2,可能需要使用“pluck”方法。因此

user_ids = UserContact.where("number = ?", '1234').pluck(:app_id).uniq
users = User.where(:id => user_ids)

第三:用红宝石代替这样做:

arr=[]
contact.each do|c|
  arr << c.app_id
end

这样做:

arr = contact.inject([]) {|arr, c| arr << c.app_id}

第四:在我的所有示例中,您的语法主要是Rails 2.我假设您使用的是rails 2?如果是这样,您可能需要升级。

FIFTH:如果返回多个对象,则使用多个变量名。因此

 contact = UserContact.....
 name=User.....

应该是

 contacts = UserContact.find.....
 users = User.find.....

LAST:

  User.joins(:user_contacts).where("user_contacts.number = ?", '1234')

可能不错

相关问题