1

当我单击退出链接时,即使该方法似乎存在,我也会收到以下错误。

NameError in SessionsController#destroy 
undefined local variable or method `sign_out' for #<SessionsController:0x007f87c8ecd8d8>

这是我的代码,会话控制器

class SessionsController < ApplicationController

  def new
  end

  def create
     user = User.find_by_email(params[:session][:email].downcase)
     if user && user.authenticate(params[:session][:password])
        # Sign the user in and redirect to the user's show page.
     else
         flash.now[:error] = 'Invalid email/password combination' # Not quite right!
        render 'new'
     end
  end

  def destroy
    sign_out
   redirect_to root_url
  end
end

会话助手

module SessionsHelper

  def sign_in(user)

    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user

    @current_user ||= User.find_by_remember_token(cookies[:remember_token])

  end

  def signed_in?
    !current_user.nil?
  end

   def sign_out
     self.current_user = nil
     cookies.delete(:remember_token)end
end

布局

<header class="navbar navbar-fixed-top navbar-inverse">
  <div class="navbar-inner">
    <div class="container">
      <%= link_to "sample app", root_path, id: "logo" %>
      <nav>
        <ul class="nav pull-right">
          <li><%= link_to "Home", root_path %></li>
          <li><%= link_to "Help", help_path %></li>
          <% if signed_in? %>
            <li><%= link_to "Users", '#' %></li>
            <li id="fat-menu" 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 "Sign out", signout_path, method: "delete" %>
                </li>
              </ul>
            </li>
          <% else %>
            <li><%= link_to "Sign in", signin_path %></li>
          <% end %>
        </ul>
      </nav>
    </div>
  </div>
</header>
4

1 回答 1

3

在会话控制器中包含会话助手。

class SessionsController < ApplicationController
  include SessionsHelper 
  ...
end

如果您想让会话助手方法在所有控制器中可用,请将其添加到应用程序控制器而不是会话控制器中。

于 2013-01-31T23:05:37.770 回答