(Rails 5.2)我使用JSON的记录在CREATE上正确地保存到(Postgres 9.4)数据库中,但是在更新后正在重新格式化,在更新后,回车返回(\r)和换行符(\n)出现在数据库中。
: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这是表格的相关部分。(该表单用于创建和更新。)如果用户希望修改默认值,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)是不可用的,因为它是作为字符串存储的:

我遗漏了什么?
发布于 2018-09-14 04:05:36
天啊。把整件事写出来多久一次能帮助你更清楚地思考!我有一个答案:在UPDATE操作中,我实际上没有使用参数的JSON.parsed版本。通过改变
if @budget.update(budget_params)至
if @budget.save(budget_params)一切都正常运作。
尽管如此,如果有人能够为JSON数据提供更优雅的编码方式(管理界面),我将很高兴听到您的建议。
发布于 2022-04-25 12:28:26
遇到了类似的情况,但在将params传递给update方法之前,通过修改params来绕过它们。所以在你的情况下:
def update
params = budget_params
params[:budget_json] = JSON.parse(params[:budget_json])
if @budget.update(params)
redirect_to admin_budgets_path, notice: "Budget successfully updated."
else
render :edit
end
endhttps://stackoverflow.com/questions/52324783
复制相似问题