I've written a couple of complex queries (at least to me) with Ruby on Rail'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 by themselves. Both return Post objects. I would like to combine these posts into a single ActiveRelation. Since there could be hundreds of thousands of posts at some point, this needs to be done at the database level. If it were a MySQL query, I could simply user the UNION
operator. Does anybody know if I can do something similar with RoR's query interface?
Post.watched_news_posts.watched_topic_posts
. You may need to send in params to the scopes for things like the:user_id
and:topic
. – Prodromefind_by_sql("#{watched_news_posts.to_sql} UNION #{watched_topic_posts.to_sql}")
. I haven't tested that out, so let me know how it goes if you try it. Also, there's probably some ARel functionality that would work. – Holmenfind_by_sql
can't be used with other chainable queries, which means I now have to rewrite my will_paginate filters and queries as well. Why doesn't ActiveRecord support aunion
operation? – Grubb