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