I have a typical elementary problems which I cannot find a nice solution for. Let’s take the typical many to many relationship in Rails, with the join table used to assign a value:
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
Nothing strange here. Let’s say now I want to to create a new recipe with new ingredients all in one go. I have some JSON sent to the server like this:
{"recipe"=>
{"name"=>"New Recipe",
"ingredients"=>
[{"name" => "new Ingr 1", "quantity"=>0.1},
{"name" => "new Ingr 2", "quantity"=>0.7}]
}
}
I reckon I can navigate the params and create the objects one by one but I was looking into leveraging the many-to-many association and above all the accepts_nested_attributes_for, thus being able to do something like Recipe.create(params[:recipe]) and have the object tree created for me. If that means changing the JSON being sent, it is not a problem. 🙂
The JSON key should be
"ingredients_attributes":and