nil:NilClass 的未定义方法“头像”

Undefined method `avatar' for nil:NilClass

我正在尝试使用回形针打印图像 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

我没有看到您在控制器操作中实例化 @user 对象的位置。你在做什么:

def edit
  @user = current_user
end

@user 这里是未定义的。您可以在控制器中定义它或使用 Devise 的 current_user 助手。

正在替换:

@user.avatar.url(:thumb)

与:

current_user.avatar.url(:thumb)

只要用户在看到此视图时已登录,就应该可以解决此错误。否则你需要在调用#avatar 之前检查是否为 nil。

当我添加此代码时,它会在以下页面上运行:

class PagesController < ApplicationController
  def index
  @user = current_user
  end

  def home
      @user = current_user
  end

  def profile
      @user = current_user
  end
end

但我想在全局所有页面上添加 :)

如果你想全局设置它,尝试在Application Controller中实现你的逻辑