Rails 4更新嵌套属性 [英] Rails 4 Update Nested Attributes
问题描述
更新嵌套属性追加而不是更新有很多关系
我正在尝试使用Rails 4 Update_attributes
Updating Nested Attributes append instead of updating in has many relationships I am trying to use Rails 4 Update_attributes
Class Person <ActiveRecord::Base
has_many :pets
accepts_nested_attributes_for :pets
end
Class Pet < ActiveRecord::Base
belongs_to :person
end
在我的控制器中,我是将参数接收为
{id:23,house_no:'22A',pets:[{name:'jeffy',type:'dog'},{name:'sharky',type:'fish'}] }
In my controller I am recieveing the params as {id: 23, house_no:'22A', pets: [{name:'jeffy', type:'dog'}, {name:'sharky', type:'fish'}]}
,而我的更新方法是
def update
@Person = Person.find(params[:id])
if @Person.update(person_params)
@Person.save
render 'persons/create', status 200
else
render 'persons/create', status 400
end
end
private
def person_params
person_params = params.permit(:house_no)
person_params.merge! ({pets_attributes: params[:pets]}) if params[:pets].present?
person_params
end
现在,当我更新
时,如果这个人已经有一只宠物
,那么新的宠物会被附加,而不是更新
,例如,如果一个ID为1的人有1只宠物命名为 Tiger
,而我将该人更新为2只宠物命名为 Shasha和 Monti,则个人记录中有3只宠物(老虎,Shasha和Monti)而不是将其更新为2(Shasha和Monti)
Now when I update it and if the person already has a pet then the new pets gets appended instead of getting updated eg if a person with id 1 has 1 pet named "Tiger" and I update that person with 2 pets named "Shasha" and "Monti" then the person record has 3 pets (Tiger, Shasha and Monti) instead of updating it to 2 (Shasha and Monti)
推荐答案
请参见手册:
http://api.rubyonrails.org/v4.0.1/classes/ActiveRecord/NestedAttributes/ClassMethods.html
您需要发送诸如 pets_attributes之类的属性:[{name:'jeffy',type:'dog'},{name:'sharky ',键入:'fish'}]
,它应该可以正常工作。
and it should work fine.
请阅读
您不能w通过成员的属性哈希值设置或更新关联帖子的属性:包括键:posts_attributes并将帖子属性的哈希值数组作为值。对于每个没有id键的哈希值,将实例化一个新记录,除非哈希还包含一个评估为true的_destroy键。
You can now set or update attributes on the associated posts through an attribute hash for a member: include the key :posts_attributes with an array of hashes of post attributes as a value.For each hash that does not have an id key a new record will be instantiated, unless the hash also contains a _destroy key that evaluates to true.
这篇关于Rails 4更新嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!