2
我希望能够在模型验证器方法中设置自定义消息,以通知用户有关错误的输入数据。Ruby on Rails。自定义验证器方法中的自定义消息
首先,我设置自定义验证类,其中我重新定义以这种方式的validate_each
方法,因为它recommended in rails' documentation:
# 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。
谢谢,塞缪尔。有用! – Shamaoke 2010-09-13 13:57:37
它不是更清洁? :) – 2010-09-14 11:34:56