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可以使用相关调查上的关系的类方法。)

在当前形式下,此代码将不起作用;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.

4

2 回答 2

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')
于 2011-09-08T23:10:22.970 回答
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)

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

于 2011-09-09T15:28:37.393 回答