2

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.

1
  • Try setting a default value with t.column :status, :ticket_status, default: nil Commented Apr 9, 2015 at 20:52

1 Answer 1

1

There is an allow_blank option.

validates :status, inclusion: { in: Ticket::STATUS.values }, allow_blank: true

http://edgeguides.rubyonrails.org/active_record_validations.html#allow-blank

Update: For this to work, you should add empty string to the enum:

CREATE TYPE ticket_status AS ENUM ('', 'submitted', 'open', 'closed');
Sign up to request clarification or add additional context in comments.

3 Comments

But an empty string is not a valid value for a column of type ticket_status so the validation will pass but the database will raise an exception. Changing the validation options is just moving the error around in this case.
Yes you are right, but empty string can be added to the database enum. I will update my answer accordingly.
Thank you! allow_blank option did the trick, but there is even more magic somewhere inside ActiveRecord class. I just changed validation rule as you suggested and Voila! Object still contains "" as value, but it's saved as NULL in database. It still looks like a bit strange to me, but at least I don't have superfluous value in ENUM definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.