Ruby on Rails FactoryGirl不生成具有多个关联的工厂



我的student_status ID存储不同的关联。 例如,student_status_id of 1 表示学生处于活动状态,因此生成这些不同的 id 是不可或缺的。 我尝试创建一个没有student_status_id 1 的 FactoryGirl 用户,代码中断告诉我没有status_id。 此外,如何使用工厂女孩生成 7 的status_id?

FactoryGirl.define do
  factory :user do
    first_name 'example'
    last_name 'user'
    email 'example@user.com'
    username 'example'
    password 'abcdef'
    password_confirmation 'abcdef'
    birthdate DateTime.new(1990,9,1,17)
    student
  end
end
FactoryGirl.define do
  factory :student_status do
    name 'Active'
    student
  end  
end    
FactoryGirl.define do
  factory :student do
    points 20
    session_minutes 120
    weekly_session_minutes 120
    can_schedule_self false
    next_monthly_cycle DateTime.new(2015,9,1,17)
    student_status_id 1
  end
end

以下是我的架构中定义的表

  create_table "student_statuses", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
  create_table "students", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "lesson_id"
    t.integer  "points"
    t.integer  "student_status_id"
    t.date     "next_monthly_cycle"
    t.integer  "session_minutes",        default: 0,    null: false
    t.date     "next_session_minutes"
    t.date     "next_session_schedule"
    t.integer  "weekly_session_minutes", default: 0,    null: false
    t.boolean  "can_schedule_self",      default: true, null: false
  end

所以你有一个 1:1 的关联,例如 student_id同时在student_status表中,student_status_idstudents表中?

试试这个:

FactoryGirl.define do
  factory(:student) do
    points 20
    session_minutes 120
    weekly_session_minutes 120
    can_schedule_self false
    next_monthly_cycle DateTime.new(2015,9,1,17)
    association(:status, factory: :student_status)
  end
end
FactoryGirl.define do
  factory(:student_status) do
    name { ['Active', 'Inactive', 'SomeOther'].sample }
  end
end

另外,请确保您在Student类中有以下内容:

belongs_to :student_status

之后,从 rails 控制台尝试此操作:

FactoryGirl.load
student = FactoryGirl.create(:student)
puts student.status # => should return actual random status

最新更新