【发布时间】:2011-09-08 22:56:10
【问题描述】:
我有以下型号:
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 上的类方法,从而可以在相关调查中使用关系。)
在当前形式下,此代码将不起作用;当我调用.map(&:survey) 时,surveys_taken 将 ActiveRelation 折叠成一个数组。有没有办法为所有加入的调查返回关系?我不能这样做:
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 访问该surveys_taken 关联。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord active-relation