我有一個查詢,它在同一個表中搜索兩個單獨的字段...查找最有可能是特定城市的位置,但也可能是一個國家...即需要兩個領域。rails union hack,如何將兩個不同的查詢結合在一起
表的樣子:
Country City
Germany Aachen
USA Amarillo
USA Austin
結果:
Keyword Sideinfo
Aachen Germany
USA Country
Austin USA
Germany Country
基本上我不知道是否有這樣做,因爲我必須使用兩個單獨的查詢,然後將它們添加了更簡潔的方式(它工作正常):
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
我找不到任何有關如何工會使用ActiveRecord ...
此問題dis在ActiveRecord中使用或僞造聯盟的方法:http://stackoverflow.com/questions/6686920/activerecord-query-union – 2014-08-05 02:17:20