使用枚举验证Rails全球化Gem

时间:2017-06-30 16:02:30

标签: ruby-on-rails validation activerecord enums globalize

当使用带有Active Record枚举的globalize gem时,我收到一个错误,好像globalize不知道枚举存在。

draw_table()

如果我这样做:

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

我收到如下错误:

  

ActiveRecord :: StatementInvalid:PG :: InvalidTextRepresentation:ERROR:整数的输入语法无效:“one”

这是因为验证,因为似乎全局化不理解枚举。

我做错了吗?我应该怎样做到这一点?

1 个答案:

答案 0 :(得分:-1)

解决方案是创建我自己的验证方法!

类似的东西:

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