我遇到的问题是,在尝试上传无效文件类型时,我的模型附件字段中的验证错误未显示在视图中。我的模型设置如下:
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?
答案 0 :(得分: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