ruby-on-rails - 无法将图像解析为 URL:to_model 委托给附件,但 Rails 5.2 中的附件为零
问题描述
我有以下表格:
<%= form_with(model: user, local: true) do |form| %>
<% if user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.file_field :avatar %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
edit
它在我的页面上被调用:
<h1>Upload Avatar</h1>
<%= image_tag(@user.avatar) %>
<%= render 'form', user: @user %>
<hr>
我在标题中收到错误,但我不确定为什么头像没有附加到user
模型上。我已经完成了所有的要求active_storage
。
has_one_attached :avatar
在user model
.
在user controller
:
def identity_params
params.permit(:email_confirmation, :password, :password_confirmation, :avatar).to_h.symbolize_keys.tap do |params|
params[:email] = params[:email_confirmation]
end
end
我也有所有必要的迁移。我错过了实际的头像附加逻辑吗?
解决方案
如果您尝试在视图中显示不存在的附件,则会收到错误消息“无法将图像解析为 URL:to_model 委托给附件,但附件为零” :
<%= image_tag(@user.avatar) %>
为避免错误,您应该这样做:
<%= image_tag(@user.avatar) if @user.avatar.attached? %>
推荐阅读
- flutter - 如何为一行中的 2 个项目的交换设置动画?
- c++ - 检查用户的输入是否等于另一个字符
- java - Thymeleaf 无法识别 HomeController 中的变量和创建 bean“homeController”时的 Java 错误
- r - 如何让 tab_model 在 Rmarkdown PDF 中正确显示?
- javascript - flex 子元素超出父容器的大小
- javascript - React 上的 Bootstrap 5:无法在“文档”上执行“querySelector”
- leaflet - 基于标记属性的草皮缓冲区样式
- rust - 是否有一种零拷贝方法来找到任意数量的集合的交集?
- concurrency - Netty 可以处理具有多个线程的单个管道吗?
- function - 为什么将调用函数提前 1 个字节会导致它发生故障?修改什么来解决?