Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中创建新的多对多嵌套模型_Ruby On Rails_Ruby On Rails 3_Nested Attributes - Fatal编程技术网

Ruby on rails 在rails中创建新的多对多嵌套模型

Ruby on rails 在rails中创建新的多对多嵌套模型,ruby-on-rails,ruby-on-rails-3,nested-attributes,Ruby On Rails,Ruby On Rails 3,Nested Attributes,我有一个典型的基本问题,我找不到一个很好的解决办法。让我们以Rails中典型的多对多关系为例,使用联接表指定值: Recipe has_many :recipe_ingredients has_many :ingredients, :through => :recipe_ingredients accepts_nested_attributes_for :recipe_ingredients Ingredient has_many :recipe_ingr

我有一个典型的基本问题,我找不到一个很好的解决办法。让我们以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}]
    }
}

我认为我可以导航参数并逐个创建对象,但我正在考虑利用多对多关联,尤其是
接受
的嵌套属性,从而能够执行类似
Recipe.create(params[:Recipe])
的操作,并为我创建对象树。如果这意味着要更改发送的JSON,那么这不是问题。:)

JSON键应该是
“成分属性”


另外,别忘了将
attr\u accessible:contracents
添加到配方模型中,否则最终会出现错误
警告:无法批量分配受保护的属性
您还需要执行
attr\u accessible:contracents\u attributes
(除非您别名了我所使用的方法,以保持JSON键不变)。无论如何,这解决了这个问题,但当我想创建两个食谱时,又出现了另一个问题,两个食谱之间共享了新的配料。。。我将创建两次相同的成分,但我认为在这种情况下,我真的必须自己导航参数/
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}]
  }
}