ActiveRecord union with Arel

Updated . Posted . Visible to the public.

I had to create a complex SQL query with rails that must return an ActiveRecord::Relation

After reading over Dan Shultz Show archive.org snapshot presentation about Arel i decided to follow the solution he provided.

beer = Beer.arel_table

union = Beer.where(name: "Oberon") \
.union(Beer.where(name: "Two Hearted")) 

Beer.from(beer.create_table_alias(union, :beers).to_sql)

so only thing i need to add is the .to_sql call (This was needed for Arel 3.0.2 for sure)

Bonyiii
Last edit
Bonyiii
Keywords
rails, arel, union
Posted by Bonyiii to Bonyiii's deck (2014-04-22 20:33)