Select from multiple tables in Rails - Has Many "articles" through [table_1, table_2]?
- by viatropos
I'm in a situation where I need to get all articles that are tied to a User through 2 tables:
article_access: gives users privilege to see an article
article_favorites: of public articles, users have favorited these
So in ActiveRecord you might have this:
class User < ActiveRecord::Base
has_many :article_access_tokens
has_many :article_favorites
def articles
unless @articles
ids = article_access_tokens.all(:select => "article_id").map(&:article_id) + article_favorites.all(:select => "article_id").map(&:article_id)
@articles = Article.send(:scoped, :conditions => {:id => ids.uniq})
end
@articles
end
end
That gives me basically an articles association which reads from two separate tables. Question is though, what's the right way to do this?
Can I somehow make 1 SQL SELECT call to do this?