rails 4.0查看当前用户if语句无法正常工作

时间:2013-10-31 13:34:36

标签: ruby-on-rails ruby ruby-on-rails-4

我的视图中有一个if语句,如果用户未登录则显示登录表单,如果是,则显示注销按钮。我是ruby和rails的新手,所以我不知道如何正确排除故障。

目前,如果我使用表单登录,我会收到登录的Flash消息,但登录表单仍然存在。如果我创建一个新用户,它会在创建时自动登录,然后退出按钮会显示在登录表单中,但是当我选择退出时,它会将我退出,将我返回到主页并闪烁注销但是注销按钮保持不变,而不是由登录表单再次替换

application.html.erb

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="/css/style.css">

</head>
<body>
    <header>
        <div class="wrapper">
            <img src="/gfx/logo.png">
            <span>Twitter Clone</span>

            <% if current_user %>
                <%= link_to "Log Out", sessions_destroy_path %>
            <% else %>
                <%= form_tag sessions_create_path do %>
                    <%= text_field_tag :username, nil, placeholder: "username" %>
                    <%= password_field_tag :password, nil,  placeholder: "password" %>
                    <%= submit_tag "Log In" %>
                <% end %>
            <% end %>

        </div>
    </header>
    <div id="content">
        <div class="wrapper">
            <% flash.each do |name, msg| %>
                <%= content_tag :div, msg, class: "flash #{name}" %>
            <% end %>
            <%= yield %>
        </div>
    </div>
    <footer>

       <div class="wrapper">
            Ribbit - A Twitter Clone in Ruby<img src="/gfx/logo-nettuts.png">
        </div>
    </footer>
</body>
</html>

application_controller.rb

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

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

helper_method :current_user
end

sessions_controller.rb

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by_username(params[:username])
        if user && user.authenticate(params[:password])
            session[:userid] = user.id
            redirect_to root_url, notice: "Logged in!"
        else
            flash[:error] = "Wrong Username or Password."
            redirect_to root_url
        end
  end

  def destroy
    session[:userid] = nil
    redirect_to root_url, notice: "Logged out."
  end
end

2 个答案:

答案 0 :(得分:1)

有一件事是你在session#create中设置session [:userid]但是你在current_user中用session [:user_id]

检查它

session [:userid]等于session [:user_id]

答案 1 :(得分:0)

这不是偶然的错误  session[:userid] = user.id 至   session[:user_id] = user.id 和   session[:user_id] = nil