0

Using Miniprofiler, I see that my blog index page is calling an SQL query for every blog post in order to find the number of votes. How can I eager load the votes so that I can consolidate these queries?

The SQL I see is something like the following for each entry.

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

In my posts_controller, I am currently eager loading the writer (Writer has_many :posts).

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

How can I add :votes to this? I have tried

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

and

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

neither of which work.

My Post model is as below

post.rb

belongs_to: :writer
has_reputation :votes, source: :writer, aggregated_by: sum
umezo
  • 1,519
  • 1
  • 19
  • 33

1 Answers1

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
nullnullnull
  • 8,039
  • 12
  • 55
  • 107