gpt4 book ai didi

ruby-on-rails - ROR 中的 JSON 数组解析

转载 作者:行者123 更新时间:2023-12-04 18:23:11 26 4
gpt4 key购买 nike

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

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 很陌生,也从网上尝试过上面的代码。不确定上面的整篇文章是否不正确,或者我遗漏了什么。请指教。谢谢。

最佳答案

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

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

整个 Action 可以这样重构:

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

关于ruby-on-rails - ROR 中的 JSON 数组解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18188043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com