Could not find the association problem in Rails

后端 未结 2 878
遇见更好的自我
遇见更好的自我 2020-12-25 10:30

I am fairly new to Ruby on Rails, and I clearly have an active record association problem, but I can\'t solve it on my own.

Given the three model classes with their

2条回答
  •  我在风中等你
    2020-12-25 11:13

    You need to include a

    has_many :form_question_answers
    

    In your FormQuestion model. The :through expects a table that's already been declared in the model.

    Same goes for your other models -- you can't supply a has_many :through association until you've first declared the has_many

    # application_form.rb
    class ApplicationForm < ActiveRecord::Base
      has_many :form_questions
      has_many :questions, :through => :form_questions
    end
    
    # question.rb
    class Question < ActiveRecord::Base
      belongs_to :section
      has_many :form_questions
      has_many :application_forms, :through => :form_questions
    end
    
    # form_question.rb
    class FormQuestion < ActiveRecord::Base
      belongs_to :question
      belongs_to :application_form
      belongs_to :question_type
      has_many :form_question_answers
      has_many :answers, :through => :form_question_answers
    end
    

    It looks like your schema might be a bit wonky, but the point is you always need to add the has_many for the join table first, then add the through.

提交回复
热议问题