0

将 globalize gem 与 A​​ctive Record 枚举一起使用时,我收到一个错误,好像 globalize 不知道枚举存在。

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

如果我做:

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

我收到如下错误:

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: 错误: 整数的无效输入语法: "one"

这是由于验证而发生的,因为 globalize 似乎不理解枚举。

难道我做错了什么?我应该如何做到这一点?

4

1 回答 1

-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
于 2017-07-05T09:00:57.650 回答