[英]Avatar image active storage Rails 6
I'm trying to setup active storage to upload an avatar when a new user register.我正在尝试设置活动存储以在新用户注册时上传头像。 I have run:我跑了:
rails active_storage:install rails db:migrate rails active_storage:安装 rails db:migrate
It's a simple app without devise.这是一个没有 devise 的简单应用程序。
I have put "has_one_attached" in model/user.rb我已将“has_one_attached”放入模型/user.rb
class User < ApplicationRecord
before_save { self.username = username.downcase }
has_one_attached :avatar
end
I have put ":avatar" in strong parameters on user controller:我在用户 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
Finally I have put the following code in my navigation view to use a generic avatar in case no user is logged in最后,我将以下代码放在导航视图中以使用通用头像,以防没有用户登录
<%= 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"%>
And in my application_helper:在我的 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
But when trying to display Im getting an error:但是当试图显示我得到一个错误时:
Showing /home/edxco/Documents/Microverse/financial_app/app/views/layouts/_nav.html.erb where line #48 raised:显示 /home/edxco/Documents/Microverse/financial_app/app/views/layouts/_nav.html.erb 其中第 48 行出现:
undefined method `avatar' for nil:NilClass 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
What I am doing wrong?我做错了什么? Could you help me, please?请问你能帮帮我吗?
Your user isn't defined.您的用户未定义。 In your helper method try the instance variable @user
that you've set in your controller instead of user
.在您的辅助方法中,尝试使用您在 controller 中设置的实例变量@user
而不是user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.