The problem is that I'm receiving empty string instead of nil as default value for enum column in PostgreSQL database, while creating new ActiveRecord object. Here is some more information.
My migration:
class CreateTickets < ActiveRecord::Migration
def change
execute <<-SQL
CREATE TYPE ticket_status AS ENUM ('submitted', 'open', 'closed');
SQL
create_table :tickets do |t|
t.string :name
t.column :status, :ticket_status
t.timestamps null: false
end
end
end
My model:
class Ticket < ActiveRecord::Base
STATUS = {
submitted: 'submitted',
open: 'open',
closed: 'closed'
}
validates :status, inclusion: { in: Ticket::STATUS.values }, allow_nil: true
end
My goal is to allow nil value in database table, but when I'm trying to create new object, I'm receiving "not included in the list error":
2.2.0 :005 > Ticket.create!
(0.8ms) BEGIN
(0.5ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Status is not included in the list
This happens because new object is created with empty string as default value in status column, while other columns get correct nil values:
2.2.0 :010 > Ticket.new
=> #<Ticket id: nil, name: nil, status: "", created_at: nil, updated_at: nil>
One more condition here, that I do want to use native PostgreSQL ENUM type, instead of integer mapping.
t.column :status, :ticket_status, default: nil