rails guide

时间:2016-07-22 15:36:33

标签: ruby-on-rails

我正在尝试将validates_with custom validations helper与Rails 4一起使用。

以下代码适用于我的应用程序:

class Photo
  validates_with CleanValidator
  include ActiveModel::Validations
end

class CleanValidator < ActiveModel::Validator
  def validate(record)
    if record.title.include? "foo"
      record.errors[:title] << "Photo failed! restricted word"
    end
  end
end 

但是我想将这个帮助器传递给多个模型中的多个属性,而不仅仅是:title

指南的validates_with部分中有一个示例,其中包含以下示例:

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if options[:fields].any?{|field| record.send(field) == "Evil" }
      record.errors[:base] << "This person is evil"
    end
  end
end

class Person < ApplicationRecord
  validates_with GoodnessValidator, fields: [:first_name, :last_name]
end

这就是我想要实现的,在我的代码示例中用[:fields]替换[:title],以便我可以将CleanValidator用于多个模型和多个属性(User.name,Photo.title等)。

1 个答案:

答案 0 :(得分:1)

我想你想要指南中的另一个例子,每个验证器。你应该可以做到

class CleanValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless ["Evil", "Other", "Restricted", "Words"].include?(value)
      record.errors[attribute] << (options[:message] || "is a restricted word")
    end
  end
end

class Photo
  include ActiveModel::Validations
  attr_accessor :title

  validates :title, clean: true
end