ruby-on-railsvalidationactiverecordenumsglobalize

Validating Rails Globalize Gem with Enum


When using the globalize gem with Active Record enums, I get an error, as if globalize doesn't know that the enum exists.

class Stuff < ActiveRecord::Base
  enum stuff_type: { one: 1, two: 2 }
  translates :name

  validates :name, presence: true, uniqueness { case_sensitive: false, scope: :stuff_type }

  default_scope do
    includes(:translations)
  end
end

If I do:

s = Stuff.new(name: 'stuff')
s.one!

I get an error as the following:

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "one"

This happens because of the validation, cause it seems like globalize doesn't understand the enum.

Am I doing something wrong? How should I accomplish this?


Solution

  • The solution was to create my own validation method!

    Something like:

    validate :name_by_type
    def name_by_type
      max_occurrences = persisted? ? 1 : 0
      occurrences = Stuff.where(stuff_type: stuff_type, name: name).count
      errors['name'] << 'Name already in use' if occurrences > max_occurrences
    end