使用枚举验证 Rails 全球化 Gem
Validating Rails Globalize Gem with Enum
将 globalize gem 与 Active 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: ERROR: invalid input syntax for integer: "one"
发生这种情况是因为验证,因为 globalize 似乎不理解枚举。
我是不是做错了什么?我该如何完成?
解决方案是创建我自己的验证方法!
类似于:
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
将 globalize gem 与 Active 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: ERROR: invalid input syntax for integer: "one"
发生这种情况是因为验证,因为 globalize 似乎不理解枚举。
我是不是做错了什么?我该如何完成?
解决方案是创建我自己的验证方法!
类似于:
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