2012-11-08 67 views
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}] 
    } 
} 

我想我可以浏览PARAMS和创建对象一个接一个,但我一直在寻找到撬动许多-to-many关联,尤其是所有accepts_nested_attributes_for ,因此能够执行诸如Recipe.create(params[:recipe])之类的操作,并为我创建对象树。如果这意味着要更改正在发送的JSON,这不是问题。 :)

回答

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}] 
    } 
} 
+0

也不要忘了加上'attr_accessible:ingredients'到配方模型,否则你会最终(警告:无法批量分配受保护的属性) – Ashitaka

+0

您还需要执行'attr_accessible:ingredients_attributes'(除非您将保留JSON密钥的方法别名保留)。无论如何,这解决了这个问题,但提出了另一个问题,当我想创建两个食谱与食谱之间共享的新成分...我会有相同的成分创建两次,但我认为在这种情况下,我将真的必须导航自我参数。 :/ – Tallmaris