我在使用Hartl的Rails教程时遇到NoMethodError
。此错误在第11章中开始显示。不确定将问题追溯到何处。这是错误消息:
NoMethodError in StaticPagesController#home undefined method `signed_in?' for #<StaticPagesController:0x007fa1b44a4ab8>
Rails.root: /Users/dbk/projects/apster
Application Trace | Framework Trace | Full Trace
app/controllers/static_pages_controller.rb:4:in `home'
这是我的StaticPagesController中的代码:
class StaticPagesController < ApplicationController
def home
if signed_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
end
这是我的ApplicationController:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
end
这是我的会话帮助文件:
module SessionsHelper
def sign_in(user)
session[:user_id] = user.id
end
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: session[:user_id])
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: cookies.signed[:user_id])
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
def logged_in?
!current_user.nil?
end
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
def sign_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
def store_location
session[:return_to] = request.url if request.get?
end
end
答案 0 :(得分:0)
NoMethodError
就是这个意思。调用了一个不存在或未加载的方法。这是因为您在logged_in?
中调用了方法SessionsHelper
。
def logged_in?
!current_user.nil?
end
但是你在signed_in?
中调用了StaticPagesController
,但这不存在,因而错误。
def home
if signed_in?
# ...
end
end