2

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

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”字段上。我在 simple_form 讨论论坛上发现了一个类似的问题,其中一个建议是使用错误助手:

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

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

4

1 回答 1

2

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

<% @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
于 2013-02-22T15:39:01.807 回答