我正在尝试将自定义验证器应用于我的模型 issue.rb:
class Issue < ActiveRecord::Base
attr_accessible :description, :no_followers, :title
validates_presence_of :title
validates_uniqueness_of :title, message: "Title should be unique!"
validates_length_of :description, minimum: 10, maximum: 50
validates_numericality_of :no_followers, allow_blank: true
validates_with YesNoValidator
end
验证器是一个位于 app/validators 的文件,包含以下内容:
class YesNoValidator < ActiveModel::Validator
def validate record
if record.title.include? "yes" && record.description.include? "No"
record.errors[:title] << "Title has the word yes and description has the word no"
end
end
end
我也尝试将它放在 lib 文件夹中,但这也给出了这个错误:
Routing Error
uninitialized constant Issue::YesNoValidator
随机 F5'ing 我有时会收到此错误:
NoMethodError in IssuesController#new
undefined method `key?' for nil:NilClass
因此,似乎未加载具有该类的文件,因此我尝试将 lib 以及 app/validators 文件夹添加到 application.rb 中的 autoload_paths 中。但这也不起作用..
有谁之前经历过这个吗?