在 Rails 3 中编写自定义验证器
我正在尝试编写一个自定义验证器来检查输入文本字段的单词数。
我试图遵循 Railscasts 第 211 集中的示例 - http://railscasts.com /episodes/211-validations-in-rails-3
因此,我创建了一个文件 /lib/word_limit_validator.rb 并复制了教程中的相同代码。我知道这段代码不计算单词数,我只是尝试使用它,因为我知道它应该如何表现。
class WordLimitValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
这是我在验证中使用的行:
validates :body, :presence => true,
:word_limit => true
当我尝试加载表单时,出现以下错误:
未知验证器:“word_limit”
如何让 Rails 识别我的验证器?
系统规格: 苹果操作系统 10.6.7 导轨3.0.4 红宝石 1.9.2p136
I'm trying to write a custom validator that will check for the number of words entered into a text field.
I was trying to follow the example in railscasts episode 211 - http://railscasts.com/episodes/211-validations-in-rails-3
So I made a file /lib/word_limit_validator.rb and copied in the same code from the tutorial. I know that this code doesn't count the number of words, I am just trying to use it because I know how it is supposed to behave.
class WordLimitValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
Here's the line I used in my validation:
validates :body, :presence => true,
:word_limit => true
When I tried to load the form I got the following error:
Unknown validator: 'word_limit'
How do I get rails to recognize my validator?
System spec:
Mac OS 10.6.7
Rails 3.0.4
ruby 1.9.2p136
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以在 Rails 项目中创建一个 app/validators 目录,并将自定义验证器放在那里。这样它们就会自动加载。
You could also create an app/validators directory in your rails project and put your custom validators there. This way they will automatically be loaded.
Rails 中不再自动加载 lib/ 中的文件。所以,你有几个选择。
config.autoload_paths += %W( #{config.root}/lib )
require File.join(Rails.root, 'lib', 'word_limit_validator')
Files in lib/ aren't autoloaded anymore in Rails. So, you have a few options.
config.autoload_paths += %W( #{config.root}/lib )
require File.join( Rails.root, 'lib', 'word_limit_validator')