我想在Rails 4中添加一个类似validates_uniqueness_of的validates_uniqueness_of助手方法。
我把它和我的zxcvbn_validator.rb放在app/验证器下面,如下所示:
require 'zxcvbn'
class ZxcvbnValidator < ActiveModel::EachValidator
...
end
# This allows us to assign the validator in the model
module ActiveModel::Validations::HelperMethods
def validates_zxcvbn(*attr_names)
validates_with ZxcvbnValidator, _merge_attributes(attr_names)
end
end但是我仍然不能在我的validates_zxcvbn中使用model.rb
错误是
lib/active_record/dynamic_matchers.rb:26:in
method_missing:未定义的人员方法validates_zxcvbn(调用'Staff.connection‘来建立连接):类(NoMethodError)
更新:
我试图将ActiveModel::Validations::HelperMethods分离到activemodel_validations_helper.rb中,并将其置于app/helpers下。然后,在我的Staff.rb模型文件中,我执行了以下操作:
class Staff < ActiveRecord::Base
include ActivemodelValidationsHelper
...
end然后,我启动了服务器并获得了以下错误:
active_support/Reliencies.rb:495:in‘load_缺失_常数’:
Unable to autoload constant ActivemodelValidationsHelper,预期的app/helpers/activemodel_validations_helper.rb定义它(LoadError)
如何在Rails 4中包含新的验证助手方法?
谢谢!
发布于 2016-04-14 18:39:22
按照客户端验证的自定义验证程序教程,它将使用
# This allows us to assign the validator in the model
module ActiveModel::Validations::HelperMethods
def validates_zxcvbn_of(*attr_names)
validates_with ZxcvbnValidator, _merge_attributes(attr_names)
end
end并将其置于config/initializer下,以便在模型中启用validates_zxcvbn_of。
此外,我已经将zxcvbn_validator.rb放在了app/validators下。
特别感谢@taglia也提到了解决方案。
发布于 2016-04-14 16:11:07
app/validators目录(您已经完成了)zxcvbn_validator.rb的文件,其内容如下:
类ZxcvbnValidator < ActiveModel::EachValidator validate_each(记录、属性、值)结果=Zxcvbn.test(值),除非result.score >0 record.errorsattribute << (选项:message "not SecurityEntific.L.“)端端端下面是一个有用的示例- https://github.com/kalmanh/zxcvbn-custom-validator
https://stackoverflow.com/questions/36619221
复制相似问题