belongs_to through associations



  • 3 Answer(s)

    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
    

    Answered on January 11, 2019.
    Add Comment

    Use has_one instead of belongs_to in your :though  validates_uniqueness_of instead of using a proper unique constraint in your database:

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

    Answered on January 11, 2019.
    Add Comment

       A belongs_to association cannot have a :through option off caching the question_id on Choice and adding a unique index to the table especially because validates_uniqueness_of is prone to race conditions.Add a custom validation to Choice that confirms that question_id matches,

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.