@user = User.find(params[:id]) # => User Object x 1
# user has many posts
@posts = @user.posts # ORM
# SELECT * FROM posts WHERE user_id = ? ---> N + "1"
# ...
@posts.each do |post| # Iterate - Post Object x N
puts post.comments.count
# SELECT COUNT(*) FROM comments WHERE post_id = ? ---> "N" + 1
end
@user = User.find(params[:id]) # => User Object x 1
# user has many posts
@posts = @user.posts.include(:comments) # ORM
# SELECT * FROM posts WHERE user_id = ? ---> N + "1"
# SELECT * FROM comments WHERE post_id IN (?, ....) ---> Cached
# ...
@posts.each do |post| # Iterate - Post Object x N
puts post.comments.count
# post.comments == Ccached
end
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up