ruby on rails - How to use nested_attributes when processing JSON? -
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." } ] } }
organization model:
has_many :nodes accepts_nested_attributes_for :nodes, reject_if: :new_record?
organization serializer:
attributes :id has_many :nodes
node serializer:
attributes :id, :title, :description
update method in organizations controller:
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
i tried adding accepts_nested_attributes_for
organization serializer, not seem correct generated error (undefined method 'accepts_nested_attributes_for'
), i've added accepts_nested_attributes_for
model , not serializer.
the code above generates error below, referring update_attributes
line in update method. doing wrong?
no implicit conversion of string integer
in debugger node_params
returns:
unpermitted parameters: id {"nodes"=>[{"id"=>101, "title"=>"gsdgdsfgsdg.", "description"=>"dgdsfgd."}, {"id"=>1, "title"=>"ertret.", "description"=>"etewtete."}]}
update: got work using following:
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
to serializer added root: :nodes_attributes
.
it works, i'm concerned including id in node_params
. safe? wouldn't possible edit id of organization
, node
(which shouldn't allowed)? would following proper solution not allowing update id's:
if organization.update_attributes(nodes_params.except(:id, nodes_attributes: [:id]))
looks super close.
your json child object 'nodes' need 'nodes_attributes'.
{ "organization": { "id": 1, "nodes_attributes": [ { "id": 1, "title": "hello", "description": "my description." }, { "id": 101, "title": "fdhgh", "description": "my description." } ] } }
Comments
Post a Comment