[英]Rails Minitest: Can I specify fixture relations via `has_many`?
我很困惑https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html#class-ActiveRecord::FixtureSet-label-Label+references+for+associations+-28belongs_to-2C+has_one-2C+has_many -29 ,特别是他们的示例,其中Pirate
model 与has_many:monkeys
关系似乎在has_many
端定义了夹具关联。
也就是说,海盗reginald
有一只monkey: george
### in pirates.yml
reginald:
name: Reginald the Pirate
monkey: george
### in monkeys.yml
george:
name: George the Monkey
pirate: reginald
但是,当我尝试类似(略有不同)的操作时,我收到错误消息。
# test/fixtures/books.yml
book_one:
title: lorem
chapters: chapter_one, chapter_two
# test/fixtures/chapters.yml
chapter_one
title: foo
chapter_two
title: bar
# Error when running fixtures/testing
ActiveRecord::Fixture::FixtureError: table "books" has no columns named "chapters"
另一个例子让我更加困惑,它似乎显示了 model 的夹具has_many:fruits
提供了在夹具中关联的水果列表。 是的,该文档在has_and_belongs_to_many
关系下显示了这个示例,但我认为它可能也适用于has_many
关系。
### in monkeys.yml
george:
id: 1
name: George the Monkey
fruits: apple, orange, grape
### in fruits.yml
apple:
name: apple
orange:
name: orange
grape:
name: grape
那我要出去吃午饭吗? 不幸的是,如果能够在has_many
端指定夹具关联会很好。
显然,fixtures 不能在父 model 之前创建关联记录。我建议查看 factory_bot 肯定可以使用回调来创建关联记录:
FactoryBot.define do
factory :monkey do
name { "George the Monkey" }
after(:create) do |monkey, evaluator|
create_list(:fruit, 5, monkey: monkey)
monkey.reload
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.