13

同じテーブル内の 2 つの個別のフィールドを検索するクエリがあります...特定の都市である可能性が最も高い場所を探していますが、国でもある可能性があります...つまり、2 つのフィールドが必要です。

表は次のようになります。

Country    City

Germany    Aachen
USA        Amarillo
USA        Austin

結果:

Keyword   Sideinfo

Aachen    Germany
USA       Country
Austin    USA
Germany   Country 

基本的に、これを行うためのより簡潔な方法があるかどうか疑問に思っています.2つの別々のクエリを使用し、それらを一緒に追加したり、並べ替えたりする必要があったためです(これは正常に機能します):

  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 を使用して結合する方法に関する情報が見つかりませんでした...

4

4 に答える 4

3

selectを使用してきちんとしたハックを見つけました。たとえば、UserとOtherUserを結合したい場合です。

User.select('id from other_users union select id')

これにより、このSQLが生成されます

"SELECT id from other_users union select id FROM users " 

条件付きのスコープがある場合は、ActiveRecord ::Relationshipwhere_valuesメソッドを使用できます

condition = OtherUser.example_condtion_scope.where_values.join(' ')
User.select("id from other_users where #{contition}")
于 2012-11-30T20:31:57.060 に答える
2

ユニオンプラグインを使用すると、これで美しく機能するようになりました。

  def self.ajax3(search)
    Location.union( [{ :select => 'city AS keyword, country AS sideinfo', 
                       :joins => :hotels, 
                       :conditions => [ 'email IS NOT NULL AND city LIKE ?', "#{search}%" ]}, 
                     { :select => 'country AS keyword, "Country" AS sideinfo', 
                       :joins => :hotels, 
                       :conditions => [ 'email IS NOT NULL AND country LIKE ?', "#{search}%" ]}] )
  end
于 2009-10-19T08:50:41.093 に答える
1

これは Rails 4 で可能になりました。

locations = Location.arel_table
hotels = Hotel.arel_table

countries = Location
                .select(locations[:country].as("keyword"))
                .joins(:hotels)
                .where(hotels[:email].not_eq(nil))
                .where(locations[:country].matches("#{search}%"))

cities = Location
            .select(locations[:city].as("keyword"))
            .joins(:hotels)
            .where(hotels[:email].not_eq(nil))
            .where(locations[:city].matches("#{search}%"))

union = countries.union(cities)

result = Location.from(locations.create_table_alias(union, :locations).to_sql)
于 2015-06-26T07:44:20.643 に答える