gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中未加载自定义验证器

转载 作者:行者123 更新时间:2023-12-04 17:36:50 24 4
gpt4 key购买 nike

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

有谁之前经历过这个吗?

最佳答案

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

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

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

关于ruby-on-rails - Ruby on Rails 中未加载自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com