postgresql - Empty string as default value for enum type column instead of nil in Rails -
the problem i'm receiving empty string instead of nil default value enum column in postgresql database, while creating new activerecord object. here more information.
my migration:
class createtickets < activerecord::migration def change execute <<-sql create type ticket_status enum ('submitted', 'open', 'closed'); sql create_table :tickets |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 allow nil value in database table, when i'm trying create new object, i'm receiving "not included in list error":
2.2.0 :005 > ticket.create! (0.8ms) begin (0.5ms) rollback activerecord::recordinvalid: validation failed: status not included in list
this happens because new object created empty string default value in status column, while other columns 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, want use native postgresql enum type, instead of integer mapping.
there allow_blank
option.
validates :status, inclusion: { in: ticket::status.values }, allow_blank: true
http://edgeguides.rubyonrails.org/active_record_validations.html#allow-blank
update: work, should add empty string enum:
create type ticket_status enum ('', 'submitted', 'open', 'closed');