Home > Blockchain >  Rails - Enumerize case insensitive
Rails - Enumerize case insensitive

Time:01-20

In a model I have in a Rails project, one field is used with Enumerize as follows:

enumerize :status, in: %i[draft active], default: :active

If I used "active" as input it works, "ACTIVE" however gives an inclusion error.

I tried to get around this by registering a before_validation callback

before_validation :downcase_fields

def downcase_fields
  status.downcase! if status.present?
end

but this doesn't work as well.

How can I make an enumerizable field case insensitive in Rails?

CodePudding user response:

Your code looks fine, You can check on console by adding debugger in downcase_fields methos. Or you can simply add the validation check : uniqueness: {case_sensitive: false}

CodePudding user response:

Enumerize doesn't allow setting any value that is not one of the original acceptable set. For example if this is how the field is set in the model

enumerize :status, in: %i[draft active], default: :active

trying status = :Active would not even set the field.

The only I could do it, was through the setter (when the value is being set)

  def status=(value)
    super(value&.downcase)
  end
  • Related