ruby - Strong params: How to process nested json code? -


i'm trying write update method processes json. json looks this:

{   "organization": {     "id": 1,     "nodes": [       {         "id": 1,         "title": "hello",         "description": "my description."       },       {         "id": 101,         "title": "fdhgh",         "description": "my description."       }     ]   } } 

my update method follows:

  def update     organization = organization.find(params[:id])     nodes = params[:organization][:nodes]     nodes.each |node|       n = node.find(node[:id])       unless n.update_attributes(node_params)         render json: organization, status: :failed       end     end     render json: diagram, status: :ok   end    private     def node_params       params.require(:organization).permit(nodes: [:title, :description])     end 

unfortunately, n.update_attributes(node_params) generates:

unpermitted parameter: id unpermitted parameter: id unpermitted parameter: id    (0.2ms)  begin    (0.3ms)  rollback *** activerecord::unknownattributeerror exception: unknown attribute 'nodes' node. 

does see i'm doing wrong , write update method?

on unless n.update_attributes(node_params) line, you're trying update node n nodes_params, of nodes json minus ids:

{"nodes"=>[{"title"=>"hello", "description"=>"my description."}, {"title"=>"fdhgh", "description"=>"my description."}]}

you add :id permitted node parameter, cut out nodes assignment step, iterate on node_params instead, , omit :id when updating node n. e.g.,

def update   organization = organization.find(params[:id])   node_params.each |node|     n = node.find(node[:id])     unless n.update_attributes(node.except(:id))       render json: organization, status: :failed     end   end   render json: diagram, status: :ok end  private   def node_params     params.require(:organization).permit(nodes: [:id, :title, :description])   end 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -