Search code examples
mysqlruby-on-railsruby-on-rails-3query-analyzer

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?


Update:

Per Taryn East's tip, I updated the User model method to:

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

  self.stars.where(post_id: post.id).exists?
  # OR post.stars.where(:user_id => self.id).exists?
end

Although this allows me to associate/cache the stars belonging to the User, I still have to use where to check if any of those stars belong to the post. Right?


Solution

  • You can reduce this kind of duplicate query by using associations - which are automatically cached by Rails.

    class Post
       has_many :stars
    
    
    class User
       def has_starred_post?(post)
         return false if post.nil?
    
         post.stars.exists?
       end
    

    Or re-organise so it makes sense to your actual object model...