【问题标题】:Uploading Profile Picture/Avatar Error using image_tag in Rails在 Rails 中使用 image_tag 上传个人资料图片/头像错误
【发布时间】:2021-04-01 02:10:05
【问题描述】:

我是 Rails 新手,我正在开发一个 Rails 应用程序。我有一个使用devise gem 创建的用户帐户。我更改了devise/registrations/edit 以允许用户更改默认的个人资料图片。但是,当我在编辑时上传图像时,它只显示图像错误图标。我已经更改了设计中允许的参数以允许头像。

我也使用了导航栏上的图像,它只显示错误图像。 我的导航栏为图像添加了以下内容: <%= image_tag user_avatar(current_user,40), class: "rounded-circle" %>

而我的application_helper.rb 有以下代码:

def user_avatar(user, size=50)
    if user.avatar.attached? 
      user.avatar.variant(resize: "#{size}×#{size}!")
    else
      image_tag 'default_avatar.png', size: size
    end
  end

这就是edit.html.erb中的样子

<div class="row">
          <div class="col-12">
            <%= image_tag user_avatar(resource, 100) %>
          </div>
   </div>

它是这样显示的:

我使用了一个教程来获得这个。 谁能告诉我为什么会出现这个图像错误?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    在你的#Gemfile
    gem 'mini_magick'

    然后在你的助手上

    def user_avatar(user, size=50)
      if user.avatar.attached? 
        user.avatar.attachment.variant(resize: "#{size}×#{size}!")
      else
       'default_avatar.png'
      end
    end
    

    另外,对于默认图片,你不需要在 helper 中再次使用 image_tag,只需返回 url。

    【讨论】:

    • 您好,谢谢!但它没有用。我已经添加了上面场景的图片。默认图片出现,只有新上传的图片不显示。
    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 2018-08-25
    • 2020-01-10
    • 2014-04-14
    • 1970-01-01
    • 2011-11-07
    • 2020-01-04
    • 2014-10-05
    相关资源
    最近更新 更多