0

我有以下型号:活动关系:通过关联检索记录?

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将加入所有完成survey_takings,而不仅仅是完成survey_takings为@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关联。

回答

1

如果我正确理解你想找到某个用户完成的调查?如果是这样,你可以这样做:

Survey.join(:survey_takings).where("survey_takings.state = 'completed'", :user => @user) 

而且它看起来像代替:

def self.surveys_taken 
where(:state => 'completed').map(&:survey) 
end 

您可能需要使用范围:

scope :surveys_taken, where(:state => 'completed') 
+0

类方法的工作原理,以及(尽管我总是用类<<自我),虽然我不知道什么额外的'.MAP(:调查) '部分是为了。它们可以像范围一样组合。 –

+0

那么,我不能使用用于surveys_taken的范围,因为那样会返回survey_takings,而不是调查。我当然可以在控制器中执行'Survey.join',但我无法在'SurveyTaking.surveys_taken'中执行此操作,因为它是一种类方法,所以不存在'@ user'。更新问题以及.. –

+0

有几百种方法可以做到这一点。我指出你在一个方向。你没有描述你想要完成的具体事情,所以很难从你的破解代码中推断出你想要的。你可以使用范围,他们不返回数组,并且看起来你有一个不需要的关联。如果你真的只是想找到一个给定的用户完成的调查,你可以用一行代码,一个简单的数据库查询,不需要额外的代码。 –

0

我想我正在寻找的是这个:

class SurveyTaking < ActiveRecord::Base 
    def self.surveys_taken 
    Survey.joins(:survey_takings).where("survey_takings.state = 'completed'").merge(self.scoped) 
    end 
end 

这样,SurveyTaking.surveys_taken返回任何人采取的调查,但@user.survey_takings.surveys_taken返回@user采取的调查。关键是merge(self.scoped)

正等待进一步的评论之前,我接受..