FactoryGirl 的混乱比比皆是:has_many 通过

Confusion Abounds with FactoryGirl: has_many through

我很难弄清楚这个错误的确切含义:

    An error occurred in a `before(:suite)` hook.
    Failure/Error: FactoryGirl.lint

    FactoryGirl::InvalidFactoryError:
      The following factories are invalid:

      * question - Validation failed: Option must 
      exist, Question must exist (ActiveRecord::RecordInvalid)  

这些是工厂:

    # question has many options through quiz
    FactoryGirl.define do
     factory :question, class: 'Question' do
       option "What color are your eyes"
     end
   end 

    # option has many questions through quiz
    FactoryGirl.define do
      factory :option, class: 'Option' do
        option "blue"
      end
    end

    # JoinTable 
    FactoryGirl.define do
      factory :quiz, class: 'Quiz' do
        option nil
        question nil
      end
    end

我的猜测是测验工厂中关联旁边的 nil 与错误有关。我试图通读 FactoryGirl 文档以了解如何创建正确的关联,但我不明白某些事情。例如:

谢谢!

编辑:

选项型号:

    class Option < ApplicationRecord
      has_many :quizzes
      has_many :questions, through: :quizzes
    end  

问题模型

   class Question < ApplicationRecord
     has_many :quizzes
     has_many :options, through: :quizzes
   end 

测验模型

    class Some::QuizQuestion < ApplicationRecord
      belongs_to :questions
      belongs_to :options
    end

我认为您需要将 class_name 选项添加到您的关系中,我很确定 Rails 不会按照您期望的方式处理 Some 命名空间到。 例如: class Some::QuizQuestion < ApplicationRecord belongs_to :some_questions, class_name: 'Some::Question' belongs_to :some_questions, through: :some_quiz_questions end 另外,第二个 belongs_to 没有意义,你在定义它之后立即重新定义 some_questions

忘了post这个问题的答案。

主要 issue/question 是:

  • 为什么下面的连接验证 table failing/returning 错误:

     * question - Validation failed: Option must 
       exist, Question must exist (ActiveRecord::RecordInvalid)  
    

正如我所怀疑的,这是因为 QuizQuestion 工厂中两个关联旁边的 nil 值:

FactoryGirl.define do
  factory :quiz, class: 'Question' do
    option nil
    question nil
  end
end 

解决方案是删除 nil 值。