我遇到的问题是,在尝试上传无效的文件类型时,模型附件字段上的验证错误未显示在 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/