2012-06-15 45 views
0

我有食谱表,配料表和一个关联表(一个配方“有和属于许多”成分和一种成分“有和属于许多”配方)。 我没有关联表的控制器或模型。在轨道上的红宝石填充关联表

我想写一个任务,用随机(但有效的)数据填充关联表。 我写了一个代码来为关联表生成有效的id,但我无法想象如何让它进入关联表(因为我没有它的模型)。

我可以以某种方式迭代食谱,并将数据添加到recipe.ingredients列表中?它会自动填充关联表吗?

到目前为止我的代码:

namespace :FillRandomAssociationData do 

desc "Fills the recipes - ingredients association table with random data" 
task :Recipe_Ingredients_Association => :environment do 
    Recipe.all.each do |rec| 
    numOfIngredientsPerRecipe = rand(3) 
    ingredientIDLimit = Ingredient.count 

    for i in 0..numOfIngredientsPerRecipe 
     ingRandId = rand(ingredientIDLimit) 
     .... This is where I got stuck... 
    end 
    end 
end 

感谢, 李

+0

你的项目中有一个特殊的文件用于填充你的数据库:'db/seeds.rb'。并且有相关的任务调用它:'rake db:seed'。你最好遵循惯例! – jdoe

回答

1

您只需要填写配方物体与它的成分,并将其保存,Rails会填补协会表:

desc "Fills the recipes - ingredients association table with random data" 
task :Recipe_Ingredients_Association => :environment do 
    Recipe.all.each do |rec| 
    numOfIngredientsPerRecipe = rand(3) 
    ingredientIDLimit = Ingredient.count 

    for i in 0..numOfIngredientsPerRecipe 
     ingRandId = rand(ingredientIDLimit) 
     rec.ingredients << Ingredient.find(ingRandId)   
    end 

    rec.save! 
    end 
end 

要小心,用这个算法ithm你可以添加几次相同的配料到配方。

+0

谢谢:)这就是我正在寻找... – user429400