【问题标题】:Nested attribute localization for error messages in Rails 4Rails 4 中错误消息的嵌套属性本地化
【发布时间】:2015-08-05 08:32:09
【问题描述】:

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

如果图像尺寸更大,默认情况下会收到以下消息: “图书附件图片太大(最多应为 3 MB)”。

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

请帮忙。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      en:  
        activerecord:    
          errors:
            models:
              book_attachment:
                attributes:
                  image:
                    size_too_big: "is too big (should be at most 3 MB)"
      

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

      【讨论】:

        猜你喜欢
        • 2012-02-07
        • 2011-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        相关资源
        最近更新 更多