Rails 5 tries to save the empty string as nil

Viewed 885

I am in the process of upgrading my Rails app from version 4.1.16 to 5.2.3

I have a column with not null constraint and default value as 0

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:

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:

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.

How can I fix this issue? I do have this issue in most of the places of my application. Thanks.

1 Answers

One solution would be to use 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.

Related