【问题标题】:Paperclip file name in validation message验证消息中的回形针文件名
【发布时间】:2011-08-10 05:35:39
【问题描述】:

这是我要在模型中做的事情:

has_attached_file :photo, :styles => self.image_sizes, :whiny => false

validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'],
                                :message => I18n.t('paperclip.invalid_image_type', :file => self.photo.original_file_name)

我找不到解决方案我应该如何在original_file_name 中获取文件名:

NameError (undefined local variable or method `photo_file_name' for #<Class:0xaafb004>):

NoMethodError (undefined method `photo' for #<Class:0xb303e7c>): 

【问题讨论】:

  • 你能在这里发布你遇到的错误

标签: ruby-on-rails validation file paperclip


【解决方案1】:

问题是self不是实例,而是

您可以使用上传的内容类型如下:

validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'],
                            :message => :inclusion

然后在你的翻译文件中,添加

activerecord.errors.models.&lt;modelname&gt;.attributes.photo.inclusion: "%{value} is not allowed"

其中 value 将替换为上传的内容类型

【讨论】:

  • 感谢您的回答,但我说的是文件名,而不是内容类型。
  • 您可以考虑修改回形针,将原始文件名传递给消息插值。
【解决方案2】:

尝试photo_file_name 而不是photo.original_file_name

更多信息请参考Method: Paperclip::Attachment#original_filename

希望对你有帮助。

【讨论】:

  • 如果这么简单,我就不会问这个问题了。很抱歉,不起作用。
【解决方案3】:
【解决方案4】:

尝试使用

self.photo.instance_read(:file_name)

有关Paperclip::Attachment#instance_read 的更多信息,请参阅文档here

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多