Last active
March 25, 2017 22:26
-
-
Save Bahanix/c378db326c398f430ef3498f22262d56 to your computer and use it in GitHub Desktop.
Avoid N+1 queries when scopes are involved
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 | |
has_many :posts | |
has_many :published_posts, -> { published }, class_name: "Post" | |
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