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

问题描述:

我的student_status标识存储不同的关联。例如,student_status_id为1意味着学生处于活动状态,所以我生成这些不同的id是不可或缺的。我试过创建一个没有student_status_id 1的FactoryGirl用户,代码打破了告诉我没有status_id。此外,如何使用FactoryGirl来生成说7的status_id?Ruby on Rails FactoryGirl不生成具有多个关联的工厂

FactoryGirl.define do 
    factory :user do 
    first_name 'example' 
    last_name 'user' 
    email '[email protected]' 
    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_idstudent_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 

之后,从铁轨控制台试试这个:

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

噢,抱歉因为那里的混乱,学生属于'student_status',这是否会产生这种关联? – 2015-01-09 23:46:42

+0

@KevinBehan你可以用你确切的模式更新你的问题吗?具体为student/student_statuses表。从查看您提供的工厂之后询问,您有1:1关联。 – gmile 2015-01-09 23:51:56

+0

我仍然收到同样的错误。当学生控制器中使用创建动作时,我会调用一个方法,这取决于student_status_id。它检查一个学生是否注册,'student_status.enrolled?',并且测试控制台告诉我'NoMethodError:undefined method'注册了吗?' for nil:NilClass' – 2015-01-09 23:59:13