简体   繁体   English

Rails 5尝试将空字符串另存为nil

[英]Rails 5 tries to save the empty string as nil

I am in the process of upgrading my Rails app from version 4.1.16 to 5.2.3 我正在将Rails应用程序从4.1.16版本升级到5.2.3

I have a column with not null constraint and default value as 0 我有一列不为空约束且默认值为0

schema.rb: schema.rb:

t.integer wait_time_minutes  default: 0, null: false

The relevant form contains the following: 相关表格包含以下内容:

 = f.select :wait_time_minutes, [15, 30, 45, 60, 90, 120], { include_blank: true }, class: 'form-control'

While submitting this form without selecting any values, the following is submitted in the params: 提交此表单而不选择任何值时,将在参数中提交以下内容:

"wait_time_minutes"=>""

And it tries to update the column with the nil: 并尝试使用nil更新列:

UPDATE "table_name" SET "wait_time_minutes" = $1, "updated_at" = $2 WHERE "table_name"."id" = $3  ["wait_time_minutes", nil], ["updated_at", "2019-06-23 05:32:28.368640"], ["id", 1445]]

Since the column has not null constraint, it raises the following exception: 由于该列没有null约束,因此会引发以下异常:

PG::NotNullViolation - ERROR:  null value in column "wait_time_minutes" violates not-null constraint

But it wasn't the way it was working before. 但这不是以前的工作方式。 It worked fine in Rails 4.1.16. 在Rails 4.1.16中运行良好。

How can I fix this issue? 如何解决此问题? I do have this issue in most of the places of my application. 在我的应用程序的大多数地方都存在这个问题。 Thanks. 谢谢。

One solution would be to use before_save 一种解决方案是使用before_save

# model.rb
before_save do
  self.wait_time_minutes ||= 0
end

If you're not familiar with ||= it's common Ruby trick to instantiate a variable if it's not already set. 如果您不熟悉||=那么通常的Ruby技巧就是实例化尚未设置的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM