Rails放置Activemodel :: validators的位置

时间:2013-02-21 11:41:01

标签: ruby-on-rails validation activemodel

这是一个两部分问题。

第一部分,如果我正在编写验证的模型是继承自ActiveRecord::Base我是否需要在该类中include ActiveModel::Validations? rails的API没有说但是yehudakatz博客中似乎暗示了这一点?

第二部分是放置这些验证器文件的最佳位置?在帮助者或作为新模型或在lib中?

我当前的验证器看起来像这样

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'

所以我认为他们不能在同一个文件中。验证的最佳实践是什么?我看了所有的钢轨演员,我读过一些博客,我还是很新的。

修改

在我的模型中我包括这个类

include ActiveModel::Validations

我的验证看起来像这样

validates_presence_of :name, :position, :gender
validate :instance_validations, :on => :create

def instance_validations
  validates_with GenderValidator    
end

只是因为你也想看到它 谢谢你!

1 个答案:

答案 0 :(得分:8)

您不需要包含ActiveModel :: Validations

我希望将验证对象保留在模型文件夹中。

因此,对于模型性别,您有一个文件gender.rb

对于验证器GenderValidator,您有文件gender_validator.rb

因此,两个文件都在模型文件夹中一起站点。

这是我的时事通讯模型的验证器

class NewsletterValidator < ActiveModel::Validator
  def validate(record)
      if record.send_test_email
        if test_email_address.blank?
          record.errors[:test_email_address] << "Test email address is blank"
        end
        if record.send_email_to_subscribers
          record.errors[:send_test_email] << "You cannot send a test and send to subscribers at the same time"
        end
      end

  end
end

在我的简报模型中,我只是

  validates_with NewsletterValidator

您的示例中存在拼写错误

你有

class GenderValidator < ActiveModel::validator

应该是

class GenderValidator < ActiveModel::Validator

注意大写字母V