代码之家  ›  专栏  ›  技术社区  ›  A.J

无法将图像解析为url:to-model委托给附件,但附件为nil rails 5.2

  •  1
  • A.J  · 技术社区  · 6 年前

    我有以下表格:

    <%= 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 
    

    我也有所有必要的迁移。我是否缺少实际的虚拟人物附加逻辑?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Paulo Belo    6 年前

    你可以得到错误信息 无法将图像解析为URL:到委派给附件的\模型,但附件为零 如果试图在视图中显示不存在的附件:

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

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

    <%= image_tag(@user.avatar) if @user.avatar.attached? %>
    
        2
  •  1
  •   Paulo Belo    6 年前

    似乎您缺少配置(因为您没有提到它):

    必须在中声明活动存储服务 config/storage.yml

    文档示例:

    local:
      service: Disk
      root: <%= Rails.root.join("storage") %>
    
    test:
      service: Disk
      root: <%= Rails.root.join("tmp/storage") %>
    
    amazon:
      service: S3
      access_key_id: ""
      secret_access_key: ""
    

    您必须通过设置告诉活动存储器要使用哪个服务 Rails.application.config.active_storage.service

    由于每个环境可能使用不同的服务,因此建议基于每个环境执行此操作。要在开发环境中使用上一个示例中的磁盘服务,可以将以下内容添加到 config/environments/development.rb :

    # Store files locally.
    config.active_storage.service = :local