関連付けを通じてbelongs_toする質問する

関連付けを通じてbelongs_toする質問する

次の関連付けが与えられた場合、モデルから が接続されているQuestionを参照する必要があります。 を使用してこのアクションを実行しようとしています。ChoiceChoicebelongs_to :question, through: :answer

class User
  has_many :questions
  has_many :choices
end

class Question
  belongs_to :user
  has_many :answers
  has_one :choice, :through => :answer
end

class Answer
  belongs_to :question
end

class Choice
  belongs_to :user
  belongs_to :answer
  belongs_to :question, :through => :answer

  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
end

私は

NameError 初期化されていない定数User::Choice

私がやろうとするときcurrent_user.choices

含めなければ問題なく動作します

belongs_to :question, :through => :answer

しかし、私はそれを使いたいのです。validates_uniqueness_of

おそらく何か単純なことを見落としているのでしょう。どなたか助けていただければ幸いです。

ベストアンサー1

以下の作業を委任することもできます:

class Company < ActiveRecord::Base
  has_many :employees
  has_many :dogs, :through => :employees
end

class Employee < ActiveRescord::Base
  belongs_to :company
  has_many :dogs
end

class Dog < ActiveRecord::Base
  belongs_to :employee

  delegate :company, :to => :employee, :allow_nil => true
end

おすすめ記事