首页 > 解决方案 > 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,表格如下所示:

表单中呈现的 TEXTAREA 的屏幕截图

正如您在此处(来自 pgAdmin)所看到的,第一条记录(id:166)是干净且可用的。它只是刚刚创建。第二条记录 (id: 167) 不可用,因为它已存储为字符串:

显示两条记录的数据库屏幕截图

我错过了什么?

标签: ruby-on-railsjson

解决方案


天哪。多久写一次整件事可以帮助您更清晰地思考!我有答案:在 UPDATE 操作中,我实际上并没有使用 JSON.parsed 版本的参数。通过改变

if @budget.update(budget_params)

if @budget.save(budget_params)

一切正常。

话虽如此,如果有人能够建议一种更优雅的方式来为 JSON 数据的这些(管理界面)往返编码,我将很高兴听到您的建议。


推荐阅读