ruby-on-rails - 在 simple_form 中显示回形针 content_type 错误

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

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

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 一起使用?

最佳答案

Uber hack,将其放在表单上方的 View 中:

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

编辑:更好的答案:

在 Controller 中执行相同的操作

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

关于ruby-on-rails - 在 simple_form 中显示回形针 content_type 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027506/

相关文章:

ruby-on-rails - Rails 回形针从其他样式生成缩略图

ruby-on-rails - Rails/paperclip 的新手 - Paperclip 不会保存

ruby-on-rails - Angularjs、Rails 4 和 Paperclip 如何获取缩略图

ruby-on-rails - 最佳调优实践,使用Puma + Heroku + Rails 4 + Ruby 2.0的经验

javascript - 如何从 View 中删除逻辑

javascript - 如何在鼠标悬停时打开菜单折叠?

html - Twitter Bootstrap - 按钮不呈现

ruby-on-rails - 知道@vendor.name 后如何使 Ruby on Rails 中的 URL 对 SEO 友好?

ruby-on-rails - Tomcat 5.5 Filter 执行抛出异常,JRuby,Rails 3.2,warbler

html - 如何使下拉菜单超出父列的宽度?