我尝试使用Paperclip gem打印图像。
当我使用views / devise / edit.html.rb进行打印时,一切看起来都不错,但是当我想在views / layout / application.html.rb中打印时,我在控制台中收到此错误:
ActionView::Template::Error (undefined method `avatar' for nil:NilClass):
7: <%= csrf_meta_tags %>
8: </head>
9: <body>
10: <%= image_tag @user.avatar.url(:thumb) %>
11: <%= yield %>
12:
13: </body>
app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb___4291648939640547438_70254980514000'
这是User.rb:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :avatar, :styles => { :medium => ["300x300>"], :thumb => ["100x100>"], :page => ["800"] }
end
这是application_controller.rb:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :avatar) }
end
end
答案 0 :(得分:1)
@user
这里未定义。您可以在控制器中定义它,也可以使用Devise的current_user
帮助器。
更换:
@user.avatar.url(:thumb)
with:
current_user.avatar.url(:thumb)
只要用户在查看此视图时已登录,就会让您通过此错误。否则,在调用#avatar之前,您需要检查nil。
答案 1 :(得分:0)
我不知道你在控制器操作中实例化@user对象的位置。你在做什么:
def edit
@user = current_user
end
答案 2 :(得分:0)
当我添加此代码时,它适用于此页面:
class PagesController < ApplicationController
def index
@user = current_user
end
def home
@user = current_user
end
def profile
@user = current_user
end
end
但是我想在全球范围内添加所有页面:)