【问题标题】:Displaying paperclip content_type errors in simple_form在 simple_form 中显示回形针 content_type 错误
【发布时间】:2013-02-22 15:27:18
【问题描述】:

我遇到了一个问题,即在尝试上传无效文件类型时,我的模型附件字段上的验证错误未显示在视图中。我的模型设置如下:

has_attached_file :avatar,
  styles: {medium: "300x300>", thumb: "100x100>"}

validates_attachment :avatar, presence: true,
  content_type: { content_type: /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/ },
  size: { in: 0..10.megabytes }

如果我在调试器中检查错误,我会看到以下内容:

(rdb:1) p @applicant.errors.to_hash
{:avatar_content_type=>["is invalid"]}

我知道验证工作正常,所以我怀疑问题出在“avatar_content_type”字段上,而不是“avatar”字段上。我找到了similar issue on the simple_form discussion forum,其中一个建议是使用错误助手:

<%= f.input :avatar %>
<%= f.error :avatar_content_type %>

这种工作,但不包括正常错误包括的标记和类,并且样式不正确。是否有一种我忽略的方法可以与 twitter bootstrap 一起使用?

【问题讨论】:

    标签: ruby-on-rails twitter-bootstrap paperclip simple-form


    【解决方案1】:

    一个 Uber 黑客,把它放在表单上方的视图中:

    <% @applicant.errors[:avatar] << "Invalid avatar upload format" if @applicant.errors[:avatar_content_type] %>
    

    编辑:更好的答案:

    在控制器中做同样的事情

    def update
      @applicant = Applicant.find(params[:id])
      if @applicant.update_attributes(params[:applicant])
        # ..
      else
        @applicant.errors[:avatar] << "Invalid avatar upload format" if @applicant.errors[:avatar_content_type]
        render :edit
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      相关资源
      最近更新 更多