繁体   English   中英

头像图片主动存储 Rails 6

[英]Avatar image active storage Rails 6

我正在尝试设置活动存储以在新用户注册时上传头像。 我跑了:

rails active_storage:安装 rails db:migrate

这是一个没有 devise 的简单应用程序。

我已将“has_one_attached”放入模型/user.rb

class User < ApplicationRecord
    before_save { self.username = username.downcase }
    has_one_attached :avatar
end

我在用户 controller 的强参数中添加了“:avatar”:

class UsersController < ApplicationController

def new
    @user = User.new
end

def edit
    @user = User.find(params[:id])
end

def update
    @user = User.find(params[:id])
    @user.avatar.attach(params[:avatar])
    if @user.update(user_params)
      flash[:notice] = "Your account information was succesfully updated"
      redirect_to user_path
    else
      render 'edit'
    end
end

def create
    @user = User.new(user_params)
    @user.avatar.attach(params[:avatar])
    if @user.save
        flash[:notice] = "Welcome to Edx Wallet"
        redirect_to user_path(@user)
    else
        render 'new'
    end
end

private
def user_params
    params.require(:user).permit(:username, :avatar)
end

最后,我将以下代码放在导航视图中以使用通用头像,以防没有用户登录

<%= image_tag user_avatar(current_user, 40), class: "lg:ml-4 mt-1 lg:mb-0 mb-1 ml-5 pointer-cursor hover:bg-gray-50"%>

在我的 application_helper 中:

 def user_avatar(user, size=40)
    if user.avatar.attached?
      user.avatar.variant(resize: "#{size}x#{size}!")
    else
      'https://randomuser.me/api/portraits/women/49.jpg'
    end
  end

但是当试图显示我得到一个错误时:

显示 /home/edxco/Documents/Microverse/financial_app/app/views/layouts/_nav.html.erb 其中第 48 行出现:

nil:NilClass 的未定义方法 `avatar'

>   def user_avatar(user, size=40)
>     if user.avatar.attached?
>       user.avatar.variant(resize: "#{size}x#{size}!")
>     else
>       'https://randomuser.me/api/portraits/women/49.jpg'
>     end
>   end

我做错了什么? 请问你能帮帮我吗?

您的用户未定义。 在您的辅助方法中,尝试使用您在 controller 中设置的实例变量@user而不是user

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM