0

我有一个典型的基本问题,我找不到一个好的解决方案。让我们看一下 Rails 中典型的多对多关系,连接表用于赋值:

Recipe
    has_many :recipe_ingredients
    has_many :ingredients, :through => :recipe_ingredients
    accepts_nested_attributes_for :recipe_ingredients

Ingredient
    has_many :recipe_ingredients
    has_many :recipes, :through => :recipe_ingredients

RecipeIngredient
    belongs_to :recipe
    belongs_to :ingredient
    attr_accessible :quantity

这里没有什么奇怪的。假设现在我想一次性创建一个包含新成分的新食谱。我有一些 JSON 像这样发送到服务器:

{"recipe"=>
    {"name"=>"New Recipe", 
     "ingredients"=>
        [{"name" => "new Ingr 1", "quantity"=>0.1},
         {"name" => "new Ingr 2", "quantity"=>0.7}]
    }
}

我认为我可以导航参数并一个一个地创建对象,但我正在研究利用多对多关联,最重要的是accepts_nested_attributes_for,因此能够做类似的事情Recipe.create(params[:recipe])并为我创建对象树。如果这意味着更改正在发送的 JSON,那不是问题。:)

4

1 回答 1

0

JSON 密钥应为"ingredients_attributes"

Recipe
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
  attr_accessible :ingredients
  accepts_nested_attributes_for :ingredients # note this

{"recipe"=>
  {"name"=>"New Recipe", 
    "ingredients_attributes"=>
      [{"name" => "new Ingr 1", "quantity"=>0.1},
       {"name" => "new Ingr 2", "quantity"=>0.7}]
  }
}
于 2012-11-08T15:43:46.767 回答