rails union hack, how to pull two different queries together rails union hack, how to pull two different queries together ruby-on-rails ruby-on-rails

rails union hack, how to pull two different queries together


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.


I found a neat hack using select . For example if you want to make a union between User and OtherUser .

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

this will generate this SQL

"SELECT id from other_users union select id FROM users " 

If you have scopes with the conditions you can use the ActiveRecord::Relation where_values method

condition = OtherUser.example_condtion_scope.where_values.join(' ')User.select("id from other_users where #{contition}")


Using the union plugin, it now works beautifully thanks:

  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