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を呼び出すと、ActiveRelation が配列に折りたたまれます.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

しかし、からその surveys_taken 関連付けにアクセスできません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 に答える