ruby on rails - ActiveRecord Query Union -
ruby on rails - ActiveRecord Query Union -
i've written couple of complex queries (at to the lowest degree me) ror's query interface:
watched_news_posts = post.joins(:news => :watched).where(:watched => {:user_id => id}) watched_topic_posts = post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})
both of these queries work fine themselves. both homecoming post objects. combine these posts single activerelation. since there hundreds of thousands of posts @ point, needs done @ database level. if mysql query, user union
operator. know if can similar ror's query interface?
here's quick little module wrote allows union multiple scopes. returns results instance of activerecord::relation.
module activerecord::unionscope def self.included(base) base.send :extend, classmethods end module classmethods def union_scope(*scopes) id_column = "#{table_name}.id" sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" union ") "#{id_column} in (#{sub_query})" end end end
here's gist: https://gist.github.com/tlowrimore/5162327
edit:as requested, here's illustration of how unionscope works:
class property < activerecord::base include activerecord::unionscope # silly, contrived scopes scope :active_nearby, -> { where(active: true).where('distance <= 25') } scope :inactive_distant, -> { where(active: false).where('distance >= 200') } # union of aforementioned scopes scope :active_near_and_inactive_distant, -> { union_scope(active_nearby, inactive_distant) } end
ruby-on-rails activerecord union activerelation
Comments
Post a Comment