在ROR中解析JSON数组对象

时间:2013-08-13 06:26:25

标签: ruby-on-rails json

我正在尝试解析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值。请指教 。感谢。

1 个答案:

答案 0 :(得分:0)

请参阅collect方法的文档。

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]