这是一个两部分的问题。
第一部分,如果我正在为其编写验证的模型继承自我ActiveRecord::Base
是否需要include ActiveModel::Validations
在该类中?Rails的API没有说,但在yehudakatz博客中似乎暗示了这一点?
第二部分是放置这些验证器文件的最佳位置?在助手下或作为新模型或在库中?
我当前的验证器看起来像这样
class GenderValidator < ActiveModel::validator
def validate(record)
cred = /(\d{6})(\d{4})(\d{1})(\d{2})/.match(record.id_number.to_s) #breaks up the id into the relevent sections namely birthdate, gender, nationality, validator.
unless cred[0][/\d{13}/] #checks to see if the id is a valid length of numbers if it isnt then skip the validation of gender
return true
else
birthdate = cred[1] #returns a 6 digit string 'yymmdd'
parsed_gender = cred[2] #returns a 4 digit string '0001-4999:female 5000-9999:male'
nationality = cred[3] # should return either a 1 or a 0 1 if the person is foreign or 0 if the person is southafrican
validate_gender(parsed_gender, record)
end
end
private
def validate_gender(parsed_gender, record)
calculate_gender = (parsed_gender <= 4999 ? :female : :male)
unless employee.gender == calculate_gender
employee.errors[:gender] << "Your id indicates you have entered the wrong gender"
end
end
end
每个人的有效身份证号码是可选的,但如果他们确实指定了它,它应该检查性别是否正确。
如果我将它保持在与员工模型相同的模型中,那么我会收到此错误
ActionController::RoutingError (uninitialized constant Employee::GenderValidator):
app/models/employee.rb:25:in `<class:Employee>'
app/models/employee.rb:1:in `<top (required)>'
lib/role_requirement_system.rb:19:in `inherited'
app/controllers/employees_controller.rb:1:in `<top (required)>'
librato-rails (0.8.1) lib/librato/rack/middleware.rb:12:in `call'
所以我认为它们不能在同一个文件中。验证的最佳实践是什么?我看了所有的 Rails 演员表,读过一些博客,但我还是个新手。
编辑
在我的模型中,我包括这个类
include ActiveModel::Validations
我的验证看起来像这样
validates_presence_of :name, :position, :gender
validate :instance_validations, :on => :create
def instance_validations
validates_with GenderValidator
end
以防万一你也想看到,谢谢!