我有以下型号:
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
目标是能够@user.survey_takings.last_survey_taken
从控制器调用。(这是人为的,但顺其自然;总的目标是能够调用@user.survey_takings
可以使用相关调查上的关系的类方法。)
在当前形式下,此代码将不起作用;surveys_taken
当我调用.map(&:survey)
. 有没有办法为所有加入的调查返回关系?我不能这样做:
def self.surveys_taken
Survey.join(:survey_takings).where("survey_takings.state = 'completed'")
end
因为@user.survey_takings.surveys_taken
将加入所有已完成的调查问卷,而不仅仅是已完成的问卷调查@user
。
我想我想要的是相当于
class User < ActiveRecord::Base
has_many :survey_takings
has_many :surveys_taken, :through => :survey_takings, :source => :surveys
end
但我无法从SurveyTaking.last_survey_taken
.