Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning computed SQL column from AR scope result
    primarykey
    data
    text
    <p>I have a named_scope that returns some user (student) records based on the number of related "grouptask" records they have made in a certain time period.</p> <p>Student model:</p> <pre><code>class Student &lt; ActiveRecord::Base set_table_name "student" set_primary_key :sid has_many :usersessions, :foreign_key =&gt; "associatedstudentsid" has_many :grouptasks, :through =&gt; :usersessions named_scope :used_in_past, lambda {|days_ago| { :conditions =&gt; ['(SELECT count(*) as total_tasks FROM grouptask WHERE creatorstudentid = sid AND creationdate &gt; ?) &gt; 0', Date.today-days_ago] }} end </code></pre> <p>Grouptask model:</p> <pre><code>class Grouptask &lt; ActiveRecord::Base set_table_name "grouptask" has_many :usersessions, :foreign_key =&gt; "associatedgrouptaskid" has_many :students, :through =&gt; :usersessions end </code></pre> <p>What I want to do is be able to access that on-the-fly "total_tasks" column from the result for each record, but simply doing "student.total_tasks" doesn't get me there, I'm guessing because that column doesn't map to an actual db column since it's constructed at the time of lookup. So how does one access these kinds of things in an AR result set?</p> <p>The use-case for this is a table with students' names and their total amount of created tasks. Right now I am doing this by finding the users that have created tasks in the past X number of days (by finding total_tasks > 0 in that time period) and then doing a for-each that just loops through those users and counts the number of tasks in that time period again. That obviously results in a lot of SQL calls that shouldn't need to be done since those totals were already calculated in order to find the accounts in the first place.</p> <p>Thanks for any help.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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