Note that there are some explanatory texts on larger screens.

plurals
  1. POActive Relation: Retrieving records through an association?
    primarykey
    data
    text
    <p>I have the following models:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :survey_takings end class SurveyTaking &lt; ActiveRecord::Base belongs_to :survey def self.surveys_taken # must return surveys, not survey_takings where(:state =&gt; 'completed').map(&amp;:survey) end def self.last_survey_taken surveys_taken.maximum(:position) # that's Survey#position end end </code></pre> <p>The goal is to be able to call <code>@user.survey_takings.last_survey_taken</code> from a controller. (That's contrived, but go with it; the general goal is to be able to call class methods on <code>@user.survey_takings</code> that can use relations on the associated surveys.)</p> <p>In its current form, this code won't work; <code>surveys_taken</code> collapses the ActiveRelation into an array when I call <code>.map(&amp;:survey)</code>. Is there some way to instead return a relation for all the joined surveys? I can't just do this:</p> <pre><code>def self.surveys_taken Survey.join(:survey_takings).where("survey_takings.state = 'completed'") end </code></pre> <p>because <code>@user.survey_takings.surveys_taken</code> would join <em>all</em> the completed survey_takings, not just the completed survey_takings for <code>@user</code>.</p> <p>I guess what I want is the equivalent of</p> <pre><code>class User &lt; ActiveRecord::Base has_many :survey_takings has_many :surveys_taken, :through =&gt; :survey_takings, :source =&gt; :surveys end </code></pre> <p>but I can't access that surveys_taken association from <code>SurveyTaking.last_survey_taken</code>.</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.
    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