ruby-on-rails - FactoryGirl 关联 ID 为 nil
问题描述
我正在尝试将 factory_girl 与关联一起使用。我有 2 个模型:account_info 和 person。AccountInfo 属于一个人,我的 account_info 工厂看起来像:
FactoryGirl.define do
factory :account_info do
entity_type 1
account_key { Faker::Twitter.user[:id] }
association :entity_id, factory: [:person]
association :social_media_site_id, factory: [:twitter]
end
end
根据文档:
You can also specify a different factory or override attributes:
factory :post do
# ...
association :author, factory: :user, last_name: "Writely"
end
The behavior of the association method varies depending on the build strategy used for the parent object.
# Builds and saves a User and a Post
post = create(:post)
post.new_record? # => false
post.author.new_record? # => false
# Builds and saves a User, and then builds but does not save a Post
post = build(:post)
post.new_record? # => true
post.author.new_record? # => false
它创建记录 Person 但 AccountInfo entity_id 保持为零。为什么?
d = FactoryGirl.create(:account_info)
d.reload
AccountInfo Load (0.5ms) SELECT "account_infos".* FROM "account_infos" WHERE "account_infos"."id" = $1 LIMIT $2 [["id", 443], ["LIMIT", 1]]
=> #<AccountInfo id: 443, entity_type: "legislator", account_key: "498133264559673104", social_media_site_id: nil, entity_id: nil, created_at: "2018-04-29 13:18:49", updated_at: "2018-04-29 13:18:49">
版本:
factory_girl_rails (4.9.0)
rails (5.1.6)
ruby (2.5.0)
解决方案
奇怪的entity=
是没有定义。您是否在 AccountInfo 模型上定义了关联?(例如belongs_to :entity
)?如果是这样,那可能是问题(或类似问题)。
推荐阅读
- python - 在 Django 中停止正在运行的函数
- java - 为什么在 JVM 中相对于超类的字段和方法解析不同?
- delphi - 在 Delphi 的动态控件中创建、销毁和计算值
- if-statement - IS 条件在 AS3 中不起作用(额外网站不允许我发布)
- r - readxl,返回值与 Excel 上的值略有不同
- python - pyspark 中的 Pandas UDF
- python - 字段 'id' 需要一个数字,但得到了
- swift - 如何在 Swift 中检查两个结构是否具有相同的泛型参数类型?
- android - 在 Android 上通过以太网 eth0 接口 Ping 和其他人
- java - 只打印java中文本第一行上的字符串