【问题标题】:Rails 3 - Factory girl gem - belongs_to and has_one relationRails 3 - 工厂女孩 gem - belongs_to 和 has_one 关系
【发布时间】:2012-03-21 17:35:58
【问题描述】:

我有 UserTeacher 模型。老师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

据我了解,这是因为我没有告诉 Factory 我的老师 belongs_to 用户。我该如何解决?

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot ruby-on-rails-3.2


    【解决方案1】:

    你应该定义关联:

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

    厂女有wonderful tutorial,推荐你看看。

    附:为什么要将那些奇怪的前缀(user_teacher_)添加到模型属性中?它看起来很丑,所以你肯定做错了什么。

    【讨论】:

    • 同意你不需要在列名前加上user_teacher_
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多