在模型中检索记录时如何减少相同查询的数量

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

我已经开始使用 query-analyzer,它警告我相同的查询。

对于上下文,我正在页面上加载 25 "posts",当前用户可以 "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

这是用户模型中的方法:

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

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

如何通过减少查询次数来满足此警告?


更新:

根据 Taryn East 的提示,我将 User 模型方法更新为:

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

虽然这允许我 associate/cache 属于用户的星星,但我仍然必须使用 where 来检查这些星星是否属于 post。对吗?

您可以通过使用关联来减少这种重复查询 - 由 Rails 自动缓存。

class Post
   has_many :stars


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

     post.stars.exists?
   end

或重新组织以使其对您的实际对象模型有意义...