5

我正在尝试将自定义验证器应用于我的模型 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 中。但这也不起作用..

有谁之前经历过这个吗?

4

2 回答 2

6

在您的 application.rb 中,将 app/validators 路径添加到自动加载路径

config.autoload_paths += [Rails.root.join('app', 'validators').to_s]

或手动要求 Issue.rb 文件中的验证器。

于 2013-04-23T16:05:11.963 回答
3

如果您还没有,请尝试重新启动 Rails 服务器,以便您在 application.rb 中的更改可能会被考虑在内。

于 2014-11-09T22:37:18.933 回答