首页 > 解决方案 > 无法将图像解析为 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 :avataruser 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 

我也有所有必要的迁移。我错过了实际的头像附加逻辑吗?

标签: ruby-on-railsformsmodelrails-activestorage

解决方案


如果您尝试在视图中显示不存在的附件,则会收到错误消息“无法将图像解析为 URL:to_model 委托给附件,但附件为零” :

<%= image_tag(@user.avatar) %>

为避免错误,您应该这样做:

<%= image_tag(@user.avatar) if @user.avatar.attached? %>

推荐阅读