Note that there are some explanatory texts on larger screens.

plurals
  1. POnamed_scope for sum of column in related table
    primarykey
    data
    text
    <p>My SQL skills are laughable at best, which is why Rails and ActiveRecord make my life a lot easier. This time, however, it probably represents a crutch that keeps me from understanding what's going on in the back end in order to know what to feed named_scope.</p> <p>I'm trying to return the top 10 records of a table that represent the highest scoring "actors" in a game. Score is calculated via Actor>Acts>Decsisons.point_value</p> <p>I can get the score for any individual actor easily enough, but the joins and sum are above my SQL understanding in order to scope it for the top 10 out of the whole db.</p> <p>Here is the Actor model as I have it currently:</p> <pre><code>class Actor &lt; ActiveRecord::Base has_many :acts, :dependent =&gt; :destroy has_many :decisions, :through =&gt; :acts, :order =&gt; 'created_at' named_scope :high_scores, { :conditions =&gt; {:finished =&gt; true}, :joins =&gt; "INNER JOIN acts ON actor.id = acts.actor_id INNER JOIN decisions on decision.id = decision.act_id", :group =&gt; 'actor.id', :select =&gt;'actors.*, SUM(acts.decisions.point_value) AS score', :order =&gt; "score DESC", :limit =&gt; 10 } end </code></pre> <p>After trying out a few things based on some posts here and on some other sites, I'm obviously not grasping what's going on or what named_scope needs to connect the dots. Some clarity would be much appreciated. Thanks.</p> <p>*Edit: Updated named_scope to what I currently have</p> <p>This now gives me the following error:</p> <blockquote> <p>Mysql::Error: Unknown column 'acts.decisions.point_value' in 'field list': SELECT actors.*, SUM(acts.decisions.point_value) AS score FROM <code>actors</code> INNER JOIN acts ON actor.id = acts.actor_id INNER JOIN decisions on decision.id = decision.act_id WHERE (<code>actors</code>.<code>finished</code> = 1) GROUP BY actor.id ORDER BY score DESC LIMIT 10</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload