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

时间:2016-01-16 00:32:59

标签: ruby json api ruby-on-rails-4 strong-parameters

我正在尝试编写一个处理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.

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

1 个答案:

答案 0 :(得分:2)

unless n.update_attributes(node_params)行上,您尝试使用n更新节点nodes_params,这些节点是您的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