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 联合的任何信息...
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.
Table looks like:
Country City
Germany Aachen
USA Amarillo
USA Austin
Result:
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
I couldn't find any information on how to unions using ActiveRecord...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ActiveRecord 本身不可能执行 UNION 查询。所以有两种解决方案:
Doing an UNION query is not natively possible with ActiveRecord. So there are two solutions :
我发现了一个使用 select 的巧妙技巧。
例如,如果您想在 User 和 OtherUser 之间建立并集。
这将生成此 SQL
如果您有条件范围,则可以使用 ActiveRecord::Relation where_values 方法
I found a neat hack using select .
For example if you want to make a union between User and OtherUser .
this will generate this SQL
If you have scopes with the conditions you can use the ActiveRecord::Relation where_values method
使用 union 插件,它现在工作得很好,谢谢:
Using the union plugin, it now works beautifully thanks:
现在 Rails 4 中可以实现这一点,
This is now possible in Rails 4,