0

我正在尝试解析 JSON 对象以在表(MySQL)中插入值。JSON 在服务器上接收,但无法读取要插入的值。它插入 NULL 值。下面是我的 rails 控制台的快照。

Started POST "/lists.json" for 192.168.1.9 at 2013-08-13 11:38:46 +0530
  Processing by ListsController#create as JSON
  Parameters: {"list"=>[{"amount"=>"120", "status"=>"done", "itemno"=>"w01", "na
me"=>"t01"}]}
WARNING: Can't verify CSRF token authenticity
   (1.0ms)  BEGIN
  SQL (1.0ms)  INSERT INTO `lists` (`amount`, `itemno`, `name`, `status`) VALUES
 (NULL, NULL, NULL, NULL)
   (103.0ms)  COMMIT

我的 lists_controller.rb 中的 Create 方法如下

def create
    lists = params[:list].collect{|key,list_attributes| List.new(list_attributes)}
    all_list_valid = true
    lists.each_with_index do |list,index|
        unless list.valid?
            all_list_valid = false
            invalid_list = lists[index]
        end
    end

    if all_list_valid
        @lists = []
        lists.each do |list|
            list.save
            @lists << list
        end
        format.html { redirect_to @list, notice: 'List was successfully created.' }
        format.json { render json: @list, status: :created, location: @list }
    else
        format.html { render action: "new" }
        format.json { render json: @list.errors, status: :unprocessable_entity }
    end
end

我不确定为什么它采用 NULL 值,即使“参数”似乎具有正确的值。请指教 。谢谢。

4

1 回答 1

0

请参阅收集方法的文档。

irb(main):008:0> parameters = {"list"=>[{"amount"=>"120", "status"=>"done", "itemno"=>"w01", "name"=>"t01"}]}
=> {"list"=>[{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}]}
irb(main):009:0> parameters["list"]
=> [{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}]
irb(main):010:0> parameters["list"].collect{|list| p list}
{"status"=>"done", "amount"=>"120", "itemno"=>"w01", "name"=>"t01"}
=> [nil]  
于 2013-08-13T06:37:04.150 回答