我想写一个处理JSON的更新方法。该JSON看起来是这样的:如何在处理JSON时使用nested_attributes?
{
"organization": {
"id": 1,
"nodes": [
{
"id": 1,
"title": "Hello",
"description": "My description."
},
{
"id": 101,
"title": "fdhgh",
"description": "My description."
}
]
}
}
组织模式:
has_many :nodes
accepts_nested_attributes_for :nodes, reject_if: :new_record?
组织串行:
attributes :id
has_many :nodes
节点串行器:在组织控制
attributes :id, :title, :description
更新方法:
def update
organization = Organization.find(params[:id])
if organization.update_attributes(nodes_attributes: node_params.except(:id))
render json: organization, status: :ok
else
render json: organization, status: :failed
end
end
private
def node_params
params.require(:organization).permit(nodes: [:id, :title, :description])
end
我也尝试添加accepts_nested_attributes_for
该组织串行,但似乎并没有因为它产生错误(undefined method 'accepts_nested_attributes_for'
)是正确的,所以我只加accepts_nested_attributes_for
到模型中并没有给串行器。
上面的代码生成以下错误,参考更新方法中的update_attributes
行。我究竟做错了什么?
no implicit conversion of String into Integer
在调试器node_params
回报:
Unpermitted parameters: id
{"nodes"=>[{"id"=>101, "title"=>"gsdgdsfgsdg.", "description"=>"dgdsfgd."}, {"id"=>1, "title"=>"ertret.", "description"=>"etewtete."}]}
更新:得到它使用的工作如下:
def update
organization = Organization.find(params[:id])
if organization.update_attributes(nodes_params)
render json: organization, status: :ok
else
render json: organization, status: :failed
end
end
private
def node_params
params.require(:organization).permit(:id, nodes_attributes: [:id, :title, :description])
end
要我加root: :nodes_attributes
串行。
现在所有的作品,但我很关心包括在node_params
的id。那安全吗?现在不可以编辑organization
和node
(不应该被允许)的ID吗? 请问下面是一个妥善的解决办法,以使其无法更新的ID:
if organization.update_attributes(nodes_params.except(:id, nodes_attributes: [:id]))
我认为你需要从params中删除节点。您无法使用update_attributes以这种方式设置节点。 – Swards