我希望能够在模型验证器方法中设置自定义消息,以通知用户不正确的输入数据.
首先,我设置了一个自定义验证器类,我按照rails的文档中的建议重新定义了该validate_each
方法:
# app/models/user.rb
# a custom validator class
class IsNotReservedValidator < ActiveModel::EachValidator
RESERVED = [
'admin',
'superuser'
]
def validate_each(record, attribute, value)
if RESERVED.include? value
record.errors[attribute] <<
# options[:message] assigns a custom notification
options[:message] || 'unfortunately, the name is reserved'
end
end
end
其次,我尝试validates
通过两种不同的方式将自定义消息传递给方法:
# a user model
class User < ActiveRecord::Base
include ActiveModel::Validations
ERRORS = []
begin
validates :name,
:is_not_reserved => true,
# 1st try to set a custom message
:options => { :message => 'sorry, but the name is not valid' }
rescue => e
ERRORS << e
begin
validates :name,
:is_not_reserved => true,
# 2nd try to set a custom message
:message => 'sorry, but the name is not valid'
rescue => e
ERRORS << e
end
ensure
puts ERRORS
end
end
但这两种方法都不起作用:
>> user = User.new(:name => 'Shamaoke')
Unknown validator: 'options'
Unknown validator: 'message'
我在哪里以及如何为自定义验证器设置自定义消息?
谢谢.
Debian GNU/Linux 5.0.6;
Ruby 1.9.2;
Ruby on Rails 3.0.0.
首先,不要include ActiveModel::Validations
,它已经包含在内ActiveRecord::Base
.其次,您没有使用:options
密钥指定验证选项,而是使用验证器的密钥进行验证.
class User < ActiveRecord::Base validates :name, :is_not_reserved => { :message => 'sorry, but the name is not valid' } end