0

ユーザーがログインしていない場合はログインフォームを表示し、ログインしている場合はログアウトボタンを表示するifステートメントをビューに持っています。私はルビーとレールに慣れていないので、これを適切にトラブルシューティングする方法がわかりません。

現在、フォームでログインすると、ログインしたフラッシュメッセージが表示されますが、ログインフォームは残ります。新しいユーザーを作成すると、作成時に自動的にログインし、ログインフォームの代わりにログアウトボタンが表示されますが、ログアウトを選択するとログアウトされ、ホームページに戻り、ログアウトが点滅しますが、ログインフォームに再度置き換えられる代わりに、ログアウトボタンが残ります

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
4

2 に答える 2

0

うっかりミスではあり session[:userid] = user.id ませ session[:user_id] = user.idsession[:user_id] = nil

于 2013-10-31T13:46:42.480 に答える