0

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 using Rich Many to Many relations(join table have an id)

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

Best practices?

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Hello Paul. Great portfolio! Thanks for introducing me to eager loading! when I'm running @articles = User.find(1).topics.map { |t| t.articles } the output is not the same as if i had run @articles = Article.find(all). After inspection on the console i found out that the output of the your solution has one more bracket: [[#<Article id: 1, user_id: 2, title: "test">]] and the original: [#<Article id: 1, user_id: 2, title: "test">]. Do you have any idea how to overcome as my partial cannot render the new variable:undefined method `model_name' for Array:Class
How are you presenting your output in your partial?
my index file looks like that <%= render :partial => @articles%> and then the parcial: <%= link_to_unless_current h(article.title), article %> <%= h(article.body) %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.