【发布时间】:2009-10-18 10:54:41
【问题描述】:
我有一个查询,它在同一个表中搜索两个单独的字段...查找最有可能是特定城市但也可能是国家/地区的位置...即需要两个字段。
表格如下:
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 进行联合的信息...
【问题讨论】:
-
这个问题讨论了在 ActiveRecord 中使用或伪造联合的方法:stackoverflow.com/questions/6686920/activerecord-query-union
标签: sql ruby-on-rails ruby activerecord union