# Models
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
# Controller
def index
# controller performs a query (the specific query doesn't matter)
# that might nor might not return any results
@posts = Post.includes(:comments).where('comments.created_at > ?', Time.now.yesterday)
respond_to do |format|
format.html # index.html.erb
end
end
# View
- @posts.each do |post|
- post.comments.each do |comment|
= comment.title
If there aren't any @posts
, the Bullet gem complains about unused eager loading of comments.
To prevent unused eager loading, I added a conditional to the controller:
@posts_with_comments = Post.where('comments.created_at > ?', Time.now.yesterday)
if @posts_with_comments.present?
@posts = Post.includes(:comments).where('comments.created_at > ?', Time.now.yesterday)
else
@posts = @post_with_comments
end
This gets rid of the Bullet complaint, but at the expense of more DB queries than with the unused eager loading. Is there a better way to conditionally use eager loading only if @posts are present?
Bullet allows you to ignore certain unused eager loading scenarios. Is this one I shouldn't care about?