Skip to content

Instantly share code, notes, and snippets.

@monfresh
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monfresh/9009832 to your computer and use it in GitHub Desktop.
Save monfresh/9009832 to your computer and use it in GitHub Desktop.
Is there a way to disable eager loading if the query doesn't return any results?
# 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?

@monfresh
Copy link
Author

Bullet allows you to ignore certain unused eager loading scenarios. Is this one I shouldn't care about?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment