belongs_to through associations

vinhboy picture vinhboy · Oct 26, 2010 · Viewed 107.5k times · Source

Given the following associations, I need to reference the Question that a Choice is attached through from the Choice model. I have been attempting to use belongs_to :question, through: :answer to perform this action.

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

I am getting

NameError uninitialized constant User::Choice

when I try to do current_user.choices

It works fine, if I don't include the

belongs_to :question, :through => :answer

But I want to use that because I want to be able to do the validates_uniqueness_of

I am probably overlooking something simple. Any help would be appreciated.

Answer

Renra picture Renra · Jul 12, 2012

You can also delegate:

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