nameerror 未定义的局部变量或方法 `log_out' 你的意思是? logout_url ruby on rails
Posted
技术标签:
【中文标题】nameerror 未定义的局部变量或方法 `log_out\' 你的意思是? logout_url ruby on rails【英文标题】:nameerror undefined local variable or method `log_out' Did you mean? logout_url ruby on railsnameerror 未定义的局部变量或方法 `log_out' 你的意思是? logout_url ruby on rails 【发布时间】:2017-12-08 02:47:06 【问题描述】:所以我正在关注 Michael Hartl 的 tutorial,当我尝试注销时,我得到了这个
"NameError in SessionsController#destroy"undefined local variable or method "log_out" for #<SessionsController:0x0000000275f290> Did you mean? logout_url
我的测试和此错误仅在我在测试中添加最后一位后才弹出,但是,我在网站上的注销功能也不起作用。
这是我的 session_helper.rb:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def destroy
session.delete(:user_id)
@current_user = nil
end
end
这是我的 session_controller:
class SessionsController < ApplicationController
def new
end
def create
#Gets user from database in lowercase & determines if user is valid
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
# Log the user in and redirect to the user's show page.
log_in user
redirect_to user
else
# Create an error message.
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
# Logs out the current user.
def destroy
log_out # undefined variable Name error
redirect_to root_url
end
end
我的应用程序控制器:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper #temporary session cookie, expires automatically upon browser close
end
我的视图/layouts/_header.html.erb(用于注销链接所在的导航栏):
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to image_tag("logo2.png", alt: "CourseBuddies logo"), root_path, id: "logo" %>
<%- # link_to "sample app", '#', id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Reviews", '#' %></li>
<li><%= link_to "About us", about_path %></li>
<%- # LOGIN & SCROLL DOWN BAR %>
<% if logged_in? %>
**<li><%= link_to "Users", users_path %></li>
<li class="dropdown">**
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
**<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>**
<li class="divider"></li>
<li>
**<%= link_to "Log out", logout_path, method: :delete %>**
</li>
</ul>
</li>
**<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>**
</ul>
</nav>
</div>
</header>
我的用户模型:
class User < ApplicationRecord
#before saving, make sure the email is in downcase
before_save self.email = email.downcase
validates :name, presence: true, length: maximum: 50
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: maximum: 255 ,
format: with: VALID_EMAIL_REGEX ,
uniqueness: case_sensitive: false
# Let's you safely store a hashed password_digest to DB,
# gives you password & password_confirmation attributes,
# an authenticate method that returns the user when pw is correct,
# otherwise false.
has_secure_password(validations:false)
validates :password, presence:true, length: minimum: 6
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end
我的用户控制器中的创建方法: 定义创建 @user = User.new(user_params) #params[:user])#user_params)
if @user.save
log_in @user
flash[:success] = "Welcome to CourseBuddies!"
redirect_to @user
else
render 'new'
end
结束
我的测试/test_helper:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
end
还有我的 user_login_test:
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
# Visit the login path.
# Verify that the new sessions form renders properly.
# Post to the sessions path with an invalid params hash.
# Verify that the new sessions form gets re-rendered and that a flash message appears.
# Visit another page (such as the Home page).
# Verify that the flash message doesn’t appear on the new page.
test "login with valid information followed by logout" do
get login_path
post login_path, params: session: email: @user.email,
password: 'password'
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
#AFTER ADDING THIS MY TEST FAILED
#after logging in, we use delete to issue a DELETE request to the logout path
#(Table 8.1) and verify that the user is logged out and redirected to the root URL
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(@user), count: 0
end
end
最后是我的路线:
Rails.application.routes.draw do
get 'sessions/new'
#ROOT, first page to show
root 'pages#home'
# maps requests for the URL/pages/home to the about us action in the Pages controller.
# By using GET we arrange for the route to respond to a GET request.
# With this we generate a about us action inside the Pages controller, automatically
# get a page at the address /pages/about us
get '/about', to: 'pages#about'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create' #signup route that responds to POST requests.
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
#resources :sessions
resources :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
对不起,代码太多了!在教程中,它说测试 users_login_test 在添加新代码后应该变成绿色,但它失败了。此外,注销不起作用并给我这个错误: image of error
如果有任何帮助,我将不胜感激!
【问题讨论】:
【参考方案1】:NameError in SessionsController#destroy"undefined local variable or SessionsController 的方法“log_out”:0x0000000275f290 你有没有 意思是?注销网址
在tutorial(参考8.3)中,sessions_helper
中的方法名是log_out
,而你把它命名为destroy
,但是调用它在sessions_controller
中为log_out
。你应该把它改成log_out
def log_out
session.delete(:user_id)
@current_user = nil
end
【讨论】:
感谢您注意到我的愚蠢错误并再次教育我,Pavan!你是最棒的!以上是关于nameerror 未定义的局部变量或方法 `log_out' 你的意思是? logout_url ruby on rails的主要内容,如果未能解决你的问题,请参考以下文章
Action Mailer NameError:未定义的局部变量或方法“smtp”
FastlaneCore::Helper::AppcenterHelper:Class (NameError) 的未定义局部变量或方法“所有者”
nameerror 未定义的局部变量或方法 `log_out' 你的意思是? logout_url ruby on rails
ruby NameError:未定义的局部变量或StartupMailer的方法`respond_to_new_founder':Class; def之前的空格问题(如char)