Ruby on rails 如何避免N+;1.

Ruby on rails 如何避免N+;1.,ruby-on-rails,activerecord,ruby-on-rails-4,active-model-serializers,Ruby On Rails,Activerecord,Ruby On Rails 4,Active Model Serializers,我正在为一个移动社交网络应用程序构建JSON API,用户可以发表一些帖子,其他用户可以对这些帖子发表喜欢和评论 class Post < ActiveRecord::Base belongs :user end class Like < ActiveRecord::Base belongs :user belongs :post, counter_cache: true end class PostSerializer < ActiveModel::Seria

我正在为一个移动社交网络应用程序构建JSON API,用户可以发表一些帖子,其他用户可以对这些帖子发表喜欢和评论

class Post < ActiveRecord::Base
  belongs :user
end

class Like < ActiveRecord::Base
  belongs :user
  belongs :post, counter_cache: true
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :description, :likes_count, :is_liked

  def likes_count
    object.likes.size   # should pull from counter_cache
  end

  # did current_user already like this post
  def is_liked
    object.likes(user_id: scope.id).exists?  # N+1
  end
end

class PostsController < ApplicationController
  def index
    @posts = Post.recent
    render json: @posts, each_serializer: PostSerializer
  end
end

# Output of JSON API to mobile client
{
  "id": 1,
  "body": "...",
  "likes_count": 10,
  "is_liked": true
}
class Post

用户登录到移动客户端,并在打开应用程序时请求获取最近的帖子,但为了能够生成带有标志“is_like”
的JSON帖子响应,我们需要发出查询,点击DB,以了解用户是否已经喜欢帖子,所以在手机屏幕上,我们会在屏幕上的每篇帖子上显示状态。

我在这里遇到了同样的问题,所以让我们看看我是否可以帮助您

当您在
Like
模型中添加
beliens\u to:post,counter\u cache:true
时,必须在
posts
表中添加一列,名为
likes\u count
type
integer

另外,请注意,当您创建或删除类似于的
时,计数器缓存会增加或减少,因此如果您的
数据库中有一些
数据
,它将无法工作。你必须这么做


我希望它能帮助你……你有没有考虑过在RIIS之类的东西中缓存喜欢的东西?您可以做的另一件事是将所喜欢的
抽象到
Post
模型中的class方法中,然后只进行查询,直到达到无法缩放的程度,然后您可以使用Redis或任何其他平台轻松地在那里插入一些缓存