Question

I am using Ruby on Rails 4 and I would like to eager load associated objects for a has_many association. That is, I have the following models:

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
end

Since I frequently retrieve comments when I load articles I would like to eager load comments each time I search for articles, for example in these cases:

# In these cases the eager loading should happen.
Article.find(1)
Article.where(:title => 'Sample text')
@current_user.articles

What is the proper way to handle this issue? How?

Was it helpful?

Solution

You should use includes method, like in following:

Article.includes(:comments).where(title: 'Sample text')

For your first case, you don't really need eager loading, since you only select one record, so this is not n+1 problem. You can just do:

article = Article.find(1)
article.comments

If you use include your articles frequently, you may define scope:

scope :with_comments, -> { includes(:comments }

and simply call it:

Article.with_comments.where(title: 'Sample text')

When your relation into which you want to include comments comes from another association, nothing changes, you can do both:

@current_user.articles.includes(:comments)

and

@current_user.articles.with_comments

OTHER TIPS

If you want comments to be eager loaded automatically whenever you load article, you can use default_scope on Article model

class Article < ActiveRecord::Base
  has_many :comments
  default_scope :include => :comments
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top