强参数:如何处理嵌套的 json 代码?

Strong params: How to process nested json code?

我正在尝试编写一个处理 JSON 的更新方法。 JSON 看起来像这样:

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

我的更新方法如下:

  def update
    organization = Organization.find(params[:id])
    nodes = params[:organization][:nodes]
    nodes.each do |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

不幸的是,n.update_attributes(node_params) 生成:

Unpermitted parameter: id
Unpermitted parameter: id
Unpermitted parameter: id
   (0.2ms)  BEGIN
   (0.3ms)  ROLLBACK
*** ActiveRecord::UnknownAttributeError Exception: unknown attribute 'nodes' for Node.

有人看到我做错了什么并编写这个更新方法吗?

unless n.update_attributes(node_params) 行,您尝试使用 nodes_params 更新节点 n,这是 JSON 中的所有节点减去 ID:

{"nodes"=>[{"title"=>"Hello", "description"=>"My description."}, {"title"=>"fdhgh", "description"=>"My description."}]}

您可以只添加 :id 作为允许的节点参数,删除 nodes 赋值步骤,而是迭代 node_params,并在以下情况下省略 :id更新节点 n。例如,

def update
  organization = Organization.find(params[:id])
  node_params.each do |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