处理JSON时如何使用nested_attributes?
我正在尝试编写一个处理JSON的更新方法。 JSON看起来像这样:
{ "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方法中的update_attributes
行。 我究竟做错了什么?
没有将String隐式转换为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]))
看起来非常接近。
您的json子对象’nodes’需要是’nodes_attributes’。
{ "organization": { "id": 1, "nodes_attributes": [ { "id": 1, "title": "Hello", "description": "My description." }, { "id": 101, "title": "fdhgh", "description": "My description." } ] } }
你可以做这种事情。 把它放在你的控制器里。
before_action do if params[:organization] params[:organization][:nodes_attributes] ||= params[:organization].delete :nodes end end
它将在params中设置正确的属性,并仍然使用所有accepts_nested_attributesfunction。