简体   繁体   English

Rails灯具 - 你如何设置外键?

[英]Rails fixtures — how do you set foreign keys?

I'm reading about Rails fixtures in this guide (thanks, trevorturk). 我正在阅读本指南中关于Rails装置的信息(谢谢,trevorturk)。 It appears you define classes in a Yaml file and they're automatically loaded into the test DB -- cool. 看来你在Yaml文件中定义了类,它们会自动加载到test数据库中 - 很酷。

But if you want to specify that this recipe belongs to that cookbook (or whatever) how do you do that? 但是如果你想指定这个食谱属于那本食谱(或其他什么)你怎么做?

Are you supposed to specify the values for cookbook.id and recipe.cookbook_id by hand in the Yaml code? 您是否应该在Yaml代码中手动指定cookbook.idrecipe.cookbook_id的值? (Just a guess -- the guide doesn't show anything like that.) Or is there a more suitable way? (只是一个猜测 - 指南没有显示那样的东西。)或者是否有更合适的方式?

You should use named fixtures, which automatically generate an id number for you where you don't provide one. 您应该使用命名的fixture,它会为您自动生成一个id号,而不提供。 These id numbers are essentially integer hashes of whatever string you use. 这些id号基本上是你使用的任何字符串的整数哈希值。 Don't add the "_id" if you're referencing the named version: 如果您引用了指定版本,请不要添加“_id”:

# recipes.yml
chicken_soup:
  cookbook: my_recipes

# cookbooks.yml
my_recipes:
  title: My Test Cookbook

Additionally, if you wish to have a many to many association ( HABTM ) you just give an array for the association in the fixture: 此外,如果您希望有多对多关联(HABTM),您只需为夹具中的关联提供一个数组:

# recipes.yml
chicken_soup:
  cookbooks: [my_recipes, another_recipe]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM