Slide 7
Slide 7 text
Preloading data and passing it down explicitly
class Post < ApplicationRecord
def rating(like_count, dislike_count)
like_count * 2 - dislike_count
end
end
posts = Post.where(id: [1, 2, 3])
# SELECT * FROM posts WHERE id IN (1, 2, 3)
post_emoticons = Emoticon.where(post_id: posts.map(&:id))
like_count_by_post_id = post_emoticons.likes.group(:post_id).count
# SELECT COUNT(*) FROM emoticons WHERE name = 'like' AND
# post_id IN (1, 2, 3) GROUP BY post_id
dislike_count_by_post_id = post_emoticons.dislikes.group(:post_id).count
# SELECT COUNT(*) FROM emoticons WHERE name = 'dislike' AND
# post_id IN (1, 2, 3) GROUP BY post_id
posts.map do |post|
post.rating(
like_count_by_post_id[post.id],
dislike_count_by_post_id[post.id]
)
end