2013-11-06 5 views
3

Im пытается засеять мой db рецептами, которые имеют has_many отношения с ингредиентами. Таблица ингредиентов имеет 4 ряда. Однако я все время сталкиваюсь с ошибками с моим кодом. Вот мой код. Я довольно новичок в рельсах, но пока не нашел решения. Я использую Rails 4 с Postgres.Посев с отношениями has_many

Ошибка

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

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

Рецепт

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

Ингредиент

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

Seed.rb (пример здесь, имеет 2 ингредиентов с содержанием в каждой строке каждого ингредиента)

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) 

ответ

11

Вы можете сделать это следующим образом:

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"}) 
0

Я не знаю, как исправить ваше решение, но я предлагаю такой подход:

# initialize new recipe 
recipe = Recipe.new(title: "", description: "", image: "") 

# build ingredients 
recipe.ingredients.build(measure: "", modifier: "", item: "", note: "") 
recipe.ingredients.build(measure: "", modifier: "", item: "", note: "") 

recipe.save 

При запуске .save по рецепту, ингредиенты будут сохранены тоже.

Смежные вопросы