0

使用Miniprofiler,我看到我的博客索引页面正在为每篇博客文章调用 SQL 查询,以查找投票数。我怎样才能急切地加载投票,以便我可以合并这些查询?

对于每个条目,我看到的 SQL 类似于以下内容。

SELECT  "rs_reputations".* FROM "rs_reputations" WHERE "rs_reputations"."reputation_name" = 'votes' AND "rs_reputations"."target_id" = 8 AND "rs_reputations"."target_type" = 'Post' LIMIT 1

在我的posts_controller 中,我目前急于加载作者(Writer has_many :posts)。

@posts = Post.includes(:writer).paginate(page: params[:page]), :per_page => 10)

我该如何添加 :votes 呢?我努力了

@posts = Post.includes(:writer, :rs_reputation).paginate(page: params[:page]), :per_page => 10)

@posts = Post.includes(:writer, :votes).paginate(page: params[:page]), :per_page => 10)

两者都不起作用。

我的帖子模型如下

post.rb

belongs_to: :writer
has_reputation :votes, source: :writer, aggregated_by: sum
4

1 回答 1

0

事实证明这很难做到,直到最新版本。在尝试之前确保您的 gem 是最新的,但是您现在可以通过使用以下方法轻松加载:

evaluated_by(reputation_name, source [, scope])

例如:

Post.evaluated_by(:votes, @writer)

可以在 github 上找到讨论线程

更新:仔细检查,这种方法对你不起作用。它急切地加载特定作者所做的所有评估,而不是每个帖子的声誉。我会对此进行更多研究,但您也可以考虑在 github 上发布您的问题。该 gem 的开发人员反应迅速,可能会在几天内为您提供解决方案。

工作解决方案:我在github上问过,得到了这个答案。它应该像这样工作。像这样查询您的帖子:

Post.find_with_reputation(:reputation_name, :all)

然后得到这样的投票值:

post.votes
于 2012-10-15T12:42:44.200 回答