简体   繁体   中英

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

It's a simple app without devise.

I have put "has_one_attached" in model/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:

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:

 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:

undefined method `avatar' for nil:NilClass

>   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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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