也许我想错了,但从概念上讲,这对我来说似乎是正确的。
我有一个配方模型与配方成分模型协会。
当用户更新他们的配方/配方成分时,我希望他们能够从表单中删除其中一种成分,发送PUT请求,该请求将删除请求中不存在的所有配方成分。同时,我希望控制器要么更新任何修改过的模型,要么保留任何未修改的模型。
请求参数看起来像这个
"recipe"=>{"id"=>67, "name"=>"Rice", "genre"=>"Staples", "recipe_ingredients_attributes"=>[{"id"=>32, "ingredient_name"=>"Rice", "measurement_unit_quantity"=>2, "measurement_unit_type"=>"cup", "recipe_id"=>67}, {"id"=>33, "ingredient_name"=>"Water", "measurement_unit_quantity"=>"1", "measurement_unit_type"=>"cup", "recipe_id"=>67}], "instructions_attributes"=>[{"id"=>33, "content"=>"Boil", "recipe_id"=>67}, {"id"=>34, "content"=>"Eat", "recipe_id"=>67}], "user_id"=>1}, "id"=>"67"}
假设他们意识到他们不想要水,他们会移除表单的那一块,前端发送一个PUT,参数如下
{"recipe"=>{"id"=>67, "name"=>"Rice", "genre"=>"Staples", "recipe_ingredients_attributes"=>[{"id"=>32, "ingredient_name"=>"Rice", "measurement_unit_quantity"=>2, "measurement_unit_type"=>"cup", "recipe_id"=>67}], "instructions_attributes"=>[{"id"=>33, "content"=>"Boil", "recipe_id"=>67}, {"id"=>34, "content"=>"Eat", "recipe_id"=>67}], "user_id"=>1}, "id"=>"67"}
由于";水";不再存在,我想删除该配方成分。更新任何实例都很好,但更新方法正确地忽略了参数中没有的任何RecipeIngredient。
我在recipes_controller中的#更新是超级简单的
def update
@recipe = Recipe.find_by_id(recipe_params[:id]).update(recipe_params)
end
我应该添加一些逻辑来检测参数中是否缺少RecipeIngredient,并删除任何确实缺少的,还是有更好的Rails方法来做到这一点?
;轨道";通过使用CCD_ 1并传递选项CCD_。
在此之后,您希望更新属性包含一个名称为_destroy
的字段,该字段上的值计算为true
。
假设Recipe
和RecipeIngredient
之间存在一对多关联
您将需要以下内容:
#配方.rb
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true
end
使用id1
更新配方并删除id1
的配料的参数将如下所示:
params = { recipe:
{
recipe_ingredients_attributes: [
# This associated record would be deleted
{ id: '1', name: "water", _destroy: 'value_that_evaluates_to_true_here' },
# This associated record would be kept/updated
{ id: '2', name: "tomatoes" }
]
}
NestedAttributes文档:此处