Rails:Activerecord:如何在errors.add中为I18n消息发送params以进行自定义验证

Sta*_*erd 3 activerecord custom-validators rails-i18n ruby-on-rails-4

我将Rails 4与Rails-i18n Gem一起使用,我想用我的语言翻译文件中的占位符替换我的硬编码字符串"300px",如config/locales/de.yml中的%{minimum_resolution}

  activerecord:
    errors:
      models:
        organisation:
          attributes:
            image:                 
              resolution_too_small:"Image Resolution should be at least %{minimum_resolution}"
Run Code Online (Sandbox Code Playgroud)

%{minimum_resolution}中的值应来自app/models/organisation.rb中的自定义验证

  def validate_minimum_image_dimensions
    if image.present?
      logo = MiniMagick::Image.open(image.path)
      minimum_resolution = 300
      unless logo[:width] > minimum_resolution || logo[:height] > minimum_resolution
        errors.add :image, :minimum_image_size
      end
    else
      return false
    end
  end
Run Code Online (Sandbox Code Playgroud)

如何从minimum_resolution获取值到我的yaml文件中?

ill*_*ist 10

试试这个,让我知道

  def validate_minimum_image_dimensions
    if image.present?
      logo = MiniMagick::Image.open(image.path)
      minimum_resolution = 300
      unless logo[:width] > minimum_resolution || logo[:height] > minimum_resolution
        errors.add :image, :resolution_too_small, minimum_resolution: minimum_resolution
      end
    else
      return false
    end
  end
Run Code Online (Sandbox Code Playgroud)

无论如何,这是语法

errors.add :field_name, :message_key, {optional_param1: value1, optional_param2: value2}
Run Code Online (Sandbox Code Playgroud)

它必须像这样定义

  activerecord:
    errors:
      models:
        [your_model]:
          attributes:
            [field_name]:                 
              [message_key]: "Image Resolution should be at least %{optional_param1} and %{optional_param2}"
Run Code Online (Sandbox Code Playgroud)