Skip to content

Instantly share code, notes, and snippets.

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