【问题标题】:Factory Girl sets wrong value for auto-increment id in associationFactory Girl 为关联中的自动增量 ID 设置了错误的值
【发布时间】:2011-11-15 15:40:57
【问题描述】:

我有两个具有一对多关联的依赖模型

class Post < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :post
end

在我的 DBMS post_id 中的 users 表中定义为外键

我写了两个黄瓜场景——第一个我(在 factory_girl 的帮助下)创建两个用户,第二个我也想创建两个用户,但创建失败,因为 factory_girl 构建依赖 post 记录,id 设置为一个但是在前面的场景中,posts 表中的两条记录被创建和删除,所以id 值应该从3 开始,而不是从1 开始。我使用pry 调试此过程并发现如果我使用FactoryGirl.build( :post ) 它会正确设置值,但如果我使用FactoryGirl.build( :user ) 关联post.id 的值始终是1。如何使用正确的id 使它成为buld 记录?

编辑

FactoryGirl.define do 

  sequence :composite_id do |n| 
    "F98F3806-#{sprintf("%04X", n)}-4C96-879C-2C6F38213D8E"
  end

  # Post 
  factory :post do
    sequence( :post_id ) { |n| "#{n}" }
    some_field "Lorem Ipsum is simply dummy text of the printing a"
    ...
  end

  # User
  factory :user do
    user_id { FactoryGirl.generate( :composite_id )}
    association :post_id, :factory => :post
    ...
  end

end

【问题讨论】:

  • 您的工厂文件是什么样的?

标签: ruby-on-rails-3 cucumber auto-increment factory-bot


【解决方案1】:

应该是association :post。 FactoryGirl 会找出 ID 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多