Skip to content

Instantly share code, notes, and snippets.

@tosik
Last active December 13, 2015 21:08
Show Gist options
  • Select an option

  • Save tosik/4975314 to your computer and use it in GitHub Desktop.

Select an option

Save tosik/4975314 to your computer and use it in GitHub Desktop.
Rails (ActiveRecord) base union
class Friendship < ActiveRecord::Base
scope :of_user, ->(user) { union(where(user1_id: user), where(user2_id: user)) }
class << self
def union(*relations)
union_clause = "(#{relations.map {|r| r.ast.to_sql }.join(') UNION (')})"
as_clause = "AS #{self.table_name}"
from "(#{union_clause}) #{as_clause}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment