使用一个查询获取多条记录

时间:2010-12-26 13:46:22

标签: ruby-on-rails activerecord

用户表:

名称姓氏

  鲍勃普雷斯利   杰米考克斯   露西布什   罗曼考克斯

查找用户

q = Query.new("Bob Presley, Cox, Lucy")
q.find_users => {0=>{:name=>"Bob", :lastname=>"Presley"}, 1=>{:lastname=>"Cox"}, 2=>{:name=>"Lucy"}}

问题:

我有很少的名字和姓氏哈希。我需要构建Activerecord查询以从该哈希中获取所有用户。

如果我有姓名和姓氏,我应该找到名字和姓氏完全相同的用户。

如果我只有姓氏或名字,我应该找到所有具有此名称或姓氏的用户。所以当我搜索:lastname =>考克斯应该归还两个用户[罗曼考克斯,杰米考克斯]

我能做到

object = []
hash = q.find_users
hash.each do |data|
 #Pseudocode
 # object << User.where(:name => if data[:lastname] exist, :lastname => if data[:name] exist)
end

但我认为这是非常低效的。我该怎么做?

环境

rails:3.0.3
红宝石:1.9.2-头
gem:meta_search https://github.com/ernie/meta_search

1 个答案:

答案 0 :(得分:1)

我确信这可以很好地重构(提示!),但是下面的代码将构造一个可以在子选择中使用的SQL。

下面的代码不会清理输入值。 请注意,您应该清理h哈希值

中的值
h =  {0=>{:name=>"Bob", :lastname=>"Presley"}, 1=>{:lastname=>"Cox"}, 2=>{:name=>"Lucy"}}
conditions = ""
h.each_pair do |k,v|
  if not conditions.empty?
    conditions += " or "
  end
  conditions += "("
  a_condition = ""
  v.each_pair do |a,b|
    if not a_condition.empty?
      a_condition += " and "
    end
    a_condition += "#{a.to_s} = '#{b}'"
  end
  conditions += a_condition
  conditions += ")"
end
conditions = "("+conditions+")"    
p conditions
# => "((name = 'Bob' and lastname = 'Presley') or (lastname = 'Cox') or (name = 'Lucy'))"

# use the generated SQL conditions to find the users
@users = User.find(:all, :conditions => "(#{conditions})")