根页面 - nil:NilClass 的未定义方法“avatar”
Root Page - undefined method `avatar' for nil:NilClass
我正在尝试在导航中的 _header 中插入头像图像。
当我尝试时收到此错误。
我收到这个错误。
undefined method `avatar' for nil:NilClass
它与我的 _header 视图中的这段代码有关。
<%= image_tag @user.avatar.url(:large) %>
如何显示头像?
您的 @user
变量为 nil,只需用条件包装此代码:
<% if @user.present? %>
<%= image_tag @user.avatar.url %>
<% end %>
根据您的问题,您可以通过以下方式解决问题:
controller/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_user #make this method available in views
def current_user
# Use find_by_id to get nil instead of an error if user doesn't exist
# you can change the session param based on your params
@current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
end
end
在视图中,您只需调用:
<%= current_user.avatar.url(:large) %>
如果你使用devise登录,你可以调用<%= current_user.avatar.url(:large) %>
而不用在你的make helper方法application_controller.rb
希望对您有所帮助
我正在尝试在导航中的 _header 中插入头像图像。
当我尝试时收到此错误。
我收到这个错误。
undefined method `avatar' for nil:NilClass
它与我的 _header 视图中的这段代码有关。
<%= image_tag @user.avatar.url(:large) %>
如何显示头像?
您的 @user
变量为 nil,只需用条件包装此代码:
<% if @user.present? %>
<%= image_tag @user.avatar.url %>
<% end %>
根据您的问题,您可以通过以下方式解决问题:
controller/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_user #make this method available in views
def current_user
# Use find_by_id to get nil instead of an error if user doesn't exist
# you can change the session param based on your params
@current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
end
end
在视图中,您只需调用:
<%= current_user.avatar.url(:large) %>
如果你使用devise登录,你可以调用<%= current_user.avatar.url(:large) %>
而不用在你的make helper方法application_controller.rb
希望对您有所帮助