0

I have a table of recipes, a table of ingredients and an association table (a recipe "has and belong to many" ingredient and an ingredient "has and belongs to many" recipe). I do not have a controller or a model for the association table.

I want to write a task that fills the association table with random (yet valid) data. I wrote a code that generates the valid ids for the association table, but I couldn't figure how to get it to go in the association table (since I don't have its model).

Can I somehow iterate over the recipes, and add the data to the recipe.ingredients list? Will it automatically fill the association table?

My code so far:

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

end

Thanks, Li

user429400
  • 3,145
  • 12
  • 49
  • 68
  • There's a special file in your project for filling your DB: `db/seeds.rb`. And there's associated task for calling it: `rake db:seed`. You'd better follow the conventions! – jdoe Jun 15 '12 at 20:23

1 Answers1

1

You just have to fill the recipe object with its ingredients, and save it, Rails will fill the association table:

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

Be careful, with this algorithm you can add several time the same ingredient to the recipe.

Baldrick
  • 23,882
  • 6
  • 74
  • 79