Rails 4 中错误消息的嵌套属性本地化

Nested attribute localization for error messages in Rails 4

我正在使用 CarrierWave 上传图片。

我有 2 个模型

class Book < ActiveRecord::Base
  has_many :book_attachments, dependent: :destroy
  accepts_nested_attributes_for :book_attachments,   allow_destroy:        true, reject_if: proc { |attributes| attributes['image'].blank?}
end


class BookAttachment < ActiveRecord::Base
  belongs_to :book
  has_many :images

  validates :image,
    :file_size => { 
    :maximum => 3.megabytes.to_i
  }

  mount_uploader :image, ImageUploader

end

我需要本地化图像大小验证的验证消息。

我在 en.yml 中给出如下内容:

en:  
  activerecord:    
    errors:
      models:
        book_attachment:
          attributes:
            image:
              too_big: The image is too big. The maximum size is 3 MB

如果图片尺寸更大,默认会收到以下信息: "Book attachments image is too big (should be at most 3 MB)".

但是。我需要获取 en.yml 文件中显示的消息。

请帮忙。

假设您已经从 wiki (https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Validate-attachment-file-size) 中实现了自定义验证器。

试试这个:

en:
  activemodel:
    errors:
      models:
        book_attachment:
          attributes:
            image:
              size_too_big: "The image is too big. The maximum size is %{file_size} MB"

或者,您也可以直接在模型上尝试验证:

class BookAttachment < ActiveRecord::Base
  belongs_to :book
  has_many :images

  mount_uploader :image, ImageUploader

  validate :image_size

  def image_size
    if image.file.size.to_i > 3.megabytes.to_i
      errors.add(:image, :size_too_big)
    end
  end
end
en:  
  activerecord:    
    errors:
      models:
        book_attachment:
          attributes:
            image:
              size_too_big: "is too big (should be at most 3 MB)"

以上对我有用。感谢@Youri 的帮助。我使用 activerecord 而不是 activemodel。