I recently started to learn ruby on rails and I was able to successfully create an app and add users with devise, also add an avatar to the user with paperclip.
Now I’m having a problem on how to display the avatar throughout the app. The avatar only displays in http:localhost:3000/users/... (within the devise folders) for exemple, but if I try to create a new page, model, controller http://localhost:3000/profile/ for exemple, using the the tag
<%= image_tag @user.avatar.url(:thumb) %>
the page will not load and will return this error
undefined method 'avatar?' for nil:NilClass
It’s probably something really simple, but I can’t figure out how to fix it.
My model user.rb looks like this:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_uniqueness_of :username
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
attr_accessible :name, :username, :email, :password, :password_confirmation, :remember_me, :avatar
attr_accessor :current_password
end
And my controller looks like this:
class UserController < ApplicationController
def profile
end
end
Thanks!
On routes.rb, you should have something like this:
On your
UserController, you should have something like this:And then you’ll be able to use
@user.avatar.url. Also, pay attention that if you don’t have a logged in user, current_user will benil, and then you will have the error you described, so please add something like this on your controller:And then, when a unauthenticated account tries to access
/profile, it’ll be redirected to the login form.