轨道工会砍,怎么拉两个不同的查询起来 [英] rails union hack, how to pull two different queries together

查看:183
本文介绍了轨道工会砍,怎么拉两个不同的查询起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有搜索两个不同的领域,在同一个表...寻找这是最有可能的一个特定城市位置的查询,也可以是一个国家...即需要两个字段。

I have a query which searches two separate fields in the same table... looking for locations which are most likely a specific city, but could also be a country... ie the need for two fields.

表是这样的:

Country    City

Germany    Aachen
USA        Amarillo
USA        Austin

结果:

Keyword   Sideinfo

Aachen    Germany
USA       Country
Austin    USA
Germany   Country

基本上,我不知道是否有一种更简洁的方式来做到这一点,因为我不得不用两个单独的查询,然后将它们添加在一起,对它们进行排序等等(其中正常工作),

Basically I'm wondering if there is a more concise way to do this because I had to use two separate queries then add them together, sort them, etc. (which works fine):

  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 ...

I couldn't find any information on how to unions using ActiveRecord...

推荐答案

做一个UNION查询不是本身可能用ActiveRecord。所以有两种解决办法:

Doing an UNION query is not natively possible with ActiveRecord. So there are two solutions :

  • Using find_by_sql to build your query as you want it. I wouldn't advise for it.
  • Using a plugin like union to do a UNION sql query.

这篇关于轨道工会砍,怎么拉两个不同的查询起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆