3

我从我的 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 表“列表”。我在控制器中修改了“创建”代码,如下所示

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 很陌生,也从网络上尝试了上面的代码。不确定上面的整个部分是否不正确或者我遗漏了一些东西。请指教。谢谢。

4

1 回答 1

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
于 2013-08-12T13:28:37.357 回答