Sharethefun
Sharethefun

Reputation: 824

Complex Active-Relation active relation Rails Join Query with multiple relational tables

I have a user model that can "follow" some tags

User
  has_many :tag_followings 
  has_many :tags, :through => :tag_followings 

Then I have some articles that have also some tags attached.

Article
  has_many :tag_attachings
  has_many :tags, :through => :tag_attachings

tag_attaching is a join table that has fields of: user_id and tag_id and tag_following is a join table that has fields of: article_id and tag_id

I'm trying to find an efficient way to find articles that have tags that the user is following.

Best practices?

Upvotes: 0

Views: 634

Answers (1)

Paul Pettengill
Paul Pettengill

Reputation: 4855

Try using :include It should help out significantly, as it will eager load records from the associated table(s).

User
  has_many :tag_followings 
  has_many :tags, :through => :tag_followings, :include => [:article]

Article
  has_many :tag_attachings
  has_many :tags, :through => :tag_attachings, :include => [:user]

Your statement to retrieve the data, might look like:

User.find(1).tags.collect { |t| t.article.id }

The executed from your log/development.log should go from:

User Load (0.3ms)  SELECT users.* FROM users WHERE (users.id = 1) LIMIT 1
Tag Load (1.2ms) SELECT tags.* FROM tags WHERE (users.tag_id =1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 3)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 7)

to:

User Load (0.3ms)  SELECT users.* FROM users WHERE (users.id = 1) LIMIT 1
Tag Load (1.2ms) SELECT tags.* FROM tags WHERE (users.tag_id =1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id IN (1,3,7))

Upvotes: 1

Related Questions