Could not find the association problem in Rails

后端 未结 2 873
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2020-12-25 11:18

    In the ApplicationForm class, you need to specify ApplicationForms's relationship to 'form_questions'. It doesn't know about it yet. Anywhere you use the :through, you need to tell it where to find that record first. Same problem with your other classes.

    So

    # 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_questions_answers
      has_many :answers, :through => :form_question_answers
    end
    

    That is assuming that's how you have it set up.

    0 讨论(0)
提交回复
热议问题