rails union hack,如何将两个不同的查询拉到一起

hol*_*den 13 ruby sql union activerecord ruby-on-rails

我有一个查询,它搜索同一个表中的两个单独的字段...寻找最有可能是特定城市的位置,但也可能是一个国家......即需要两个字段.

表看起来像:

Country    City

Germany    Aachen
USA        Amarillo
USA        Austin
Run Code Online (Sandbox Code Playgroud)

结果:

Keyword   Sideinfo

Aachen    Germany
USA       Country
Austin    USA
Germany   Country 
Run Code Online (Sandbox Code Playgroud)

基本上我想知道是否有更简洁的方法来做到这一点因为我必须使用两个单独的查询然后将它们添加在一起,对它们进行排序等等(这很好):

  def self.ajax(search)
    countries = Location.find(:all, :select=> 'country AS keyword,  "Country" AS sideinfo', :joins => :hotels, :conditions => [ 'hotels.email IS NOT NULL AND country LIKE ?', "#{search}%" ], :group => :country )
    cities = Location.find(:all, :select=> 'city AS keyword, country AS sideinfo', :joins => :hotels, :conditions => [ 'hotels.email IS NOT NULL AND city LIKE ?', "#{search}%" ], :group => :city )
    out = cities + countries
    out = out.sort { |a,b| a.keyword <=> b.keyword }
    out.first(8)
  end
Run Code Online (Sandbox Code Playgroud)

我找不到任何关于如何使用ActiveRecord工会的信息......

Dam*_*IEU 7

使用ActiveRecord本身不可能执行UNION查询.所以有两种解决方案:

  • 使用find_by_sql根据需要构建查询.我不会建议.
  • 使用像union这样的插件来做一个UNION sql查询.

  • 联盟现在已经3岁了.任何人都有一个更新的解决方案 (4认同)