我最近开始在rails上学习ruby,我能够成功创建一个应用程序并添加设计用户,还可以使用paperclip为用户添加头像。
现在我遇到了如何在整个应用程序中显示头像的问题。例如,头像仅显示在http:localhost:3000/users/...
(在设计文件夹中)中,但如果我尝试使用标记
http://localhost:3000/profile/
例如
<%= image_tag @user.avatar.url(:thumb) %>
页面将无法加载并将返回此错误
undefined method 'avatar?' for nil:NilClass
这可能非常简单,但我无法弄清楚如何修复它。
我的模型user.rb
如下所示:
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
我的控制器看起来像这样:
class UserController < ApplicationController
def profile
end
end
谢谢!
答案 0 :(得分:2)
在routes.rb上,你应该有这样的东西:
match "profile" => "user#profile"
在UserController
上,你应该有这样的话:
class UserController < ApplicationController
def profile
@user = current_user
end
end
然后你就可以使用@user.avatar.url
了。此外,请注意,如果您没有登录用户,current_user将为nil
,然后您将收到您所描述的错误,因此请在您的控制器上添加以下内容:
class UserController < ApplicationController
before_filter :authenticate_user!
def profile
@user = current_user
end
end
然后,当未经身份验证的帐户尝试访问/profile
时,它会被重定向到登录表单。
答案 1 :(得分:0)
我还是Rails的新手,如果我错了,请纠正我,但我认为这对你有用。
class UserController < ApplicationController
def profile
@user = User.find(current_user.username)
end
end