ROR中的JSON数组解析

时间:2013-08-12 13:18:57

标签: ruby-on-rails json

我从我的Android应用程序中获取以下格式的JSON

{"list":[{"itemno":"w01","name":"t01","amount":"120","status":"done"},{"itemno":"w02","name":"t02","amount":"120","status":"done"},{"itemno":"w03","name":"t03,"amount":"120","status":"done""}]}

我需要解析这个插入mysql表“list”。我在我的控制器中修改了“创建”代码,如下所示

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

但它无法解析JSON,因此不调用create方法。我是ROR的新手,也是从网上尝试上面的代码。不确定上面的整件是不正确还是我遗漏了什么。请指教。感谢。

1 个答案:

答案 0 :(得分:3)

此外,您可以稍微重构一下代码:

# This part of code
@lists = []
lists.each do |list|
  list.save
  @lists << list
end
# Can be shortened:
lists.map(&:save)
@lists = lists

整个动作可以像这样重构:

def create
  lists = params[:list].each{ |list_attributes| List.new(list_attributes) }
  valid, not_valid = lists.partition{ |list| list.valid? }

  if not_valid.blank?
    lists.map(&:save)
    @lists = lists
    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