Skip to content

Instantly share code, notes, and snippets.

@Bahanix
Last active March 25, 2017 22:27
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 Bahanix/0f6e57c50598498e08cb8fa0d3e57e2f to your computer and use it in GitHub Desktop.
Save Bahanix/0f6e57c50598498e08cb8fa0d3e57e2f to your computer and use it in GitHub Desktop.
Avoid N+1 queries with compose option
class User < ActiveRecord::Base
# Only this class changed
has_many :posts, compose: :published
end
class Post < ActiveRecord::Base
belongs_to :user
scope :published, -> { where(status: :published) }
end
User.limit(10).preload(:published_posts).each do |user|
user.published_posts.each do |post|
puts post.title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment