Rails:Activerecord:如何在 errors.add 内发送 I18n 消息的参数以进行自定义验证

Rails: Activerecord : How to send params for I18n message inside errors.add for custom validation

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

  activerecord:
    errors:
      models:
        organisation:
          attributes:
            image:                 
              resolution_too_small:"Image Resolution should be at least %{minimum_resolution}"

%{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

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

试试这个,然后告诉我

  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

无论如何,这是语法

errors.add :field_name, :message_key, {optional_param1: value1, optional_param2: value2}

而且必须这样定义

  activerecord:
    errors:
      models:
        [your_model]:
          attributes:
            [field_name]:                 
              [message_key]: "Image Resolution should be at least %{optional_param1} and %{optional_param2}"

Rails 6+ :

语法是

errors.add :field_name, :message_key, optional_param1: value1, optional_param2: value2