代码之家  ›  专栏  ›  技术社区  ›  Ash

在Rails中找不到关联问题

  •  34
  • Ash  · 技术社区  · 15 年前

    我是RubyonRails的新手,显然我有一个活动记录关联问题,但我无法独自解决它。

    给定三个模型类及其关联:

    # application_form.rb
    class ApplicationForm < ActiveRecord::Base
      has_many :questions, :through => :form_questions
    end
    
    # question.rb
    class Question < ActiveRecord::Base
      belongs_to :section
      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 :answers, :through => :form_question_answers
    end
    

    但当我执行控制器向申请表中添加问题时,我得到了错误:

    ActiveRecord::HasManyThroughAssociationNotFoundError in Application_forms#show
    
    Showing app/views/application_forms/show.html.erb where line #9 raised:
    
    Could not find the association :form_questions in model ApplicationForm
    

    有人能指出我做错了什么吗?

    2 回复  |  直到 15 年前
        1
  •  71
  •   Jim    15 年前

    在ApplicationForm类中,您需要指定ApplicationForms与“form_questions”的关系。它还不知道。无论你在哪里使用 :through ,您需要先告诉它在哪里找到该记录。其他课程也有同样的问题。

    所以

    # 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
    

        2
  •  15
  •   bensie    15 年前

    你需要包括一个

    has_many :form_question_answers
    

    在你的问题模型中。:through需要一个已经在模型中声明的表。

    你的其他型号也一样——你不能提供 has_many :through 在您首次声明 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