ruby-on-rails - Rails:从数据库到 TEXTAREA 的 JSON 往返在第二次保存时转换为字符串
问题描述
(Rails 5.2)我的 JSON 记录在 CREATE 上正确保存到(Postgres 9.4)数据库,但在 UPDATE 后重新格式化,回车符(\r)和换行符(\n)在 UPDATE 后显示在数据库中。
: budget_json列是jsonb类型。
这是我的(简化的)预算模型:
class Budget < ApplicationRecord
after_initialize :create_shell_json
def create_shell_json
self.budget_json = blank_budget if self.new_record?
end
def blank_budget
{
id: nil,
name: nil,
year: nil,
[etc...]
}
end
end
这是我的控制器:
def new
@budget = Budget.new(year: Time.now.year)
end
def create
@budget = Budget.new(budget_params)
@budget.budget_json = JSON.parse(budget_params[:budget_json])
if @budget.save
redirect_to admin_budgets_path, notice: "Budget successfully created."
else
render :new
end
end
def edit
@budget = Budget.find(params[:id])
end
def update
@budget = Budget.find(params[:id])
@budget.budget_json = JSON.parse(budget_params[:budget_json])
if @budget.update(budget_params)
redirect_to admin_budgets_path, notice: "Budget successfully updated."
else
render :edit
end
end
以下是表格的相关部分。(CREATE 和 UPDATE 的形式相同。)如果用户想要修改默认值,TEXTAREA 包含可编辑的 JSON:
<%= form_with model: [:admin, @budget], local: true, :html => {:class => "form-horizontal"} do |f| %>
...
<div class="form-group">
<div class="col-sm-2">
<%= f.label :budget_json %>
</div>
<div class="col-sm-2">
<%= text_area_tag "budget[budget_json]", JSON.pretty_generate(@budget.budget_json), id: "budget_budget_json" %>
</div>
</div>
...
<% end %>
FWIW,表格如下所示:
正如您在此处(来自 pgAdmin)所看到的,第一条记录(id:166)是干净且可用的。它只是刚刚创建。第二条记录 (id: 167) 不可用,因为它已存储为字符串:
我错过了什么?
解决方案
天哪。多久写一次整件事可以帮助您更清晰地思考!我有答案:在 UPDATE 操作中,我实际上并没有使用 JSON.parsed 版本的参数。通过改变
if @budget.update(budget_params)
到
if @budget.save(budget_params)
一切正常。
话虽如此,如果有人能够建议一种更优雅的方式来为 JSON 数据的这些(管理界面)往返编码,我将很高兴听到您的建议。
推荐阅读
- .net - VB.NET 如何将锯齿状数组作为一维数组访问?
- c# - 带有 VS Android 模拟器的锐龙 3
- javascript - 无法从实时数据库 Firebase 中迭代子节点?
- c# - WCF 服务(NetTcpBinding)+ 托管 WPF 应用程序上的主机
- android - Why 32 bit and 64 bit Android application give different /proc/cpuinfo : feature list
- reactjs - 无法使用 getFieldDecorator 在输入字段上写入
- junit5 - 如何从 TestExecutionListener 访问测试方法注释
- java - 如何使用正则表达式收集日志的不同部分
- visual-studio-code - 自动缩进不适用于 SAS 语言扩展
- javascript - 从 props 数组中按索引值删除