2012-03-21 53 views
1

我有用户教师模型。教师belongs_to用户和用户has_one老师。我也有在工厂女孩文件中的代码:Rails 3 - 工厂女孩宝石 - belongs_to和has_one的关系

Factory.define :user do |user| 
    user.user_login "Another User" 
    user.user_role "admin" 
    user.password "foobar" 
end 

Factory.sequence :user_login do |n| 
    "person-#{n}" 
end 

Factory.define :teacher do |teacher| 
    teacher.teacher_last_name 'Last' 
    teacher.teacher_first_name 'First' 
    teacher.teacher_middle_name 'Middle' 
    teacher.teacher_birthday '01.11.1980' 
    teacher.teacher_category 'First category' 
    teacher.teacher_sex   'm' 
end 

当我尝试创建我的规格老师:

@teacher = Factory(:teacher) 

然后我收到错误:

Failure/Error: @teacher = Factory(:teacher) 
    ActiveRecord::RecordInvalid: 
     Validation failed: User can't be blank 

正如我明白这一点,因为我不告诉工厂,我的老师belongs_to用户。我该如何解决这个问题?

回答

6

你应该定义的关联:

Factory.define :teacher do |teacher| 
    ... 
    teacher.user 
end 

工厂女孩有wonderful tutorial,我建议你看看吧。

P.S.为什么要将这些奇怪的前缀(user_,teacher_)添加到模型属性?它看起来非常难看,所以你一定做错了什么。

+0

同意你不需要在'user_'和'teacher_'前添加列名。 – 2012-09-14 18:04:41