Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeding with a has_many relationship

Im trying to seed my db with recipes that has a has_many relationship with ingredients. The ingredient table has 4 rows. I keep running into errors with my code however. Here's my code. I'm fairly new to rails but could not find a solution yet. I'm using Rails 4 with Postgres.

The Error

rake aborted!
Ingredient(#xxxxxxx) expected, got Hash(#xxxxxxx)

Tasks: TOP => db:seed
(See full trace by running task with --trace)

Recipe

class Recipe < ActiveRecord::Base
   attr_accessible :title, :descrition, :image
   has_many :ingredients
   accepts_nested_attributes_for :ingredients
end

Ingredient

class Ingredient < ActiveRecord::Base
   attr_accessible :measure, :modifier, :item, :note
   belongs_to :recipe
end

Seed.rb (example here has 2 ingredients with content in each row of each ingredient)

Recipe.create(
[{
    title: "Recipe title here", 
    description: "This is the description", 
    image: "theimage.jpg", 
    ingredients_attributes: [{measure: "1cup", modifier: "canned", item: "Mushrooms", note: "drained"}, {measure: "1lb", modifier: "sliced", item: "Bacon", note: "previously cooked"},]
}], 
without_protection: true)
like image 333
Yesthe Cia Avatar asked Dec 11 '22 10:12

Yesthe Cia


1 Answers

You can do it this way:

recipe = Recipe.create({
    title: "Recipe title here", 
    description: "This is the description", 
    image: "theimage.jpg"})

recipe.ingredients.create(measure: "1cup", modifier: "canned", item: "Mushrooms", note: "drained")
recipe.ingredients.create(measure: "1lb", modifier: "sliced", item: "Bacon", note: "previously cooked"})
like image 115
cortex Avatar answered Dec 29 '22 16:12

cortex