如何在自定义验证中使用验证?

时间:2011-06-06 15:29:45

标签: ruby ruby-on-rails-3 validation

我使用easy_globalize3_accessor设置翻译字段,我想测试一组这样的字段:

class ClientTemplate < ActiveRecord::Base
  validates :content, :subject, :translated_presence => {:locales => Proc.new{|template| template.client.languages.map(&:locale)}}
end

所以我创建了一个像这样的新自定义验证器,但似乎不起作用:

class TranslatedPresenceValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    (options[:locales].call(record) || I18n.available_locales).each do |locale|
      record.class.validates "#{attribute}_#{locale}".to_sym, :presence => true
    end
  end
end

问题很简单,如何调用验证?

感谢。

更新:

validates :content, :subject, :no_internationalization_blank => {
    :locales => Proc.new{|template| template.client.languages.map(&:locale)}
}

使用:

class NoInternationalizationBlankValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    options[:locales].call(record).each do |locale|
      record.errors[attribute] << I18n.t("activerecord.errors.messages.blank_internationalization", 
  :language => I18n.t("languages.%s" % locale).downcase) if record.send(attribute.to_s.concat("_%s" % locale)).blank?
    end
  end
end

1 个答案:

答案 0 :(得分:0)

你能试试吗?

[...]
record.class.instance_eval do
  validates "#{attribute}_#{locale}".to_sym, :presence => true
end
[...]