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

时间:2015-08-05 08:32:09

标签: ruby ruby-on-rails-4 internationalization carrierwave nested-attributes

我正在使用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

如果图片大小更多,默认情况下会收到以下消息:     &#34;图书附件图片太大(最多3 MB)&#34;。

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

请帮忙。

2 个答案:

答案 0 :(得分:0)

假设您已经从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

答案 1 :(得分:0)

en:  
  activerecord:    
    errors:
      models:
        book_attachment:
          attributes:
            image:
              size_too_big: "is too big (should be at most 3 MB)"

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