Skip to content

Instantly share code, notes, and snippets.

@chrise86
Forked from javiertoledo/README.txt
Last active August 29, 2015 14:10
Show Gist options
  • Save chrise86/a5864d71c1dd9d7fd0a0 to your computer and use it in GitHub Desktop.
Save chrise86/a5864d71c1dd9d7fd0a0 to your computer and use it in GitHub Desktop.
Add union_hack.rb to your project, for example at lib folder and ensure you're loading it on your application.rb file:
# You'll need to add something like that
config.autoload_paths += %W(#{config.root}/lib)
Then extend your favourite model with the module and you'll be able to do unions with unique records, sorted by any fields and limited in number of records (see my_timeline_method):
class Profile < ActiveRecord::Base
extend UnionHack
has_many :events
has_many :friends
has_many :friend_events, :through => :friends, :source => :events
def my_timeline
Profile.union([events, friend_events], :distinct => true, :order => 'created_at DESC', :limit => 20)
end
end
module UnionHack
def union(relations, opts={})
query = 'SELECT '+ (opts[:distinct] ? 'DISTINCT ' : '' ) +'* FROM ((' + relations.map { |r| r.ast.to_sql }.join(') UNION (') + ')) AS t'
query << " ORDER BY #{opts[:order]}" if opts[:order]
query << " LIMIT #{opts[:limit]}" if opts[:limit]
find_by_sql(query)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment