Last active
March 25, 2017 22:27
-
-
Save Bahanix/0f6e57c50598498e08cb8fa0d3e57e2f to your computer and use it in GitHub Desktop.
Avoid N+1 queries with compose option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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