dimanche 10 juillet 2016

How to reduce number of identical queries when retrieving records in model

I have started using query-analyzer and it's warning me about identical queries.

For context, I am loading 25 "posts" on the page, and the current user can "star" a post:

0.018s 25 identical queries SELECT SQL_NO_CACHE N AS one FROM 'stars' WHERE 'stars'.'post_id' = N AND 'stars'.'user_id' = N LIMIT N

This is the method in the User model:

def has_starred_post?(post)
  return false if post.nil?

  Star.where(post_id: post.id, user_id: self.id).exists?
end

How can I satisfy this warning by reducing the number of queries?

Aucun commentaire:

Enregistrer un commentaire