Rails fixtures — how do you set foreign keys?

安稳与你 提交于 2019-12-18 03:49:09

问题


I'm reading about Rails fixtures in this guide (thanks, trevorturk). It appears you define classes in a Yaml file and they're automatically loaded into the test DB -- cool.

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? (Just a guess -- the guide doesn't show anything like that.) Or is there a more suitable way?


回答1:


You should use named fixtures, which automatically generate an id number for you where you don't provide one. These id numbers are essentially integer hashes of whatever string you use. Don't add the "_id" if you're referencing the named version:

# recipes.yml
chicken_soup:
  cookbook: my_recipes

# cookbooks.yml
my_recipes:
  title: My Test Cookbook



回答2:


Additionally, if you wish to have a many to many association ( HABTM ) you just give an array for the association in the fixture:

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


来源:https://stackoverflow.com/questions/510195/rails-fixtures-how-do-you-set-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!