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

Turns out this was difficult to do, up until the latest release. Make sure you're gem is up-to-date before trying this, but you can now eager load fairly easily by using:

evaluated_by(reputation_name, source [, scope])

For instance:

Post.evaluated_by(:votes, @writer)

The discussion thread can be found here on github.

UPDATE: On closer examination, this method won't work for you. It eager loads all evaluations made by a particular writer, as opposed to the reputations for each post. I'll look into this more, but you might also consider posting your question on github. The developer for this gem is very responsive and will likely have a solution for you within a couple of days.

WORKING SOLUTION: I asked on github, and got this answer. It should work like this. Query for your posts like so:

Post.find_with_reputation(:reputation_name, :all)

And then get the vote values like this:

post.votes
于 2012-10-15T12:42:44.200 に答える