来自RUBY ON RAILS TUTORIAL,Michael Hartl。第7章
我有一个问题。如果操作员不工作
我试图做新的应用程序,但仍然没有
application.html.erb:
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", '#' %></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>
session_helper.rb:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
def remember(user)
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: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, 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
# Logs out the current user.
def log_out
session.delete(:user_id)
@current_user = nil
end
end
users_controller.rb:
class UsersController < ApplicationController
before_action :correct_user, only: [:edit, :update]
def index
@users = User.all
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts(page: params[:page])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
我猜logged_in
不起作用,但我找不到错误。
当我定义注销方法时,该按钮不会从“登录”
答案 0 :(得分:0)
您的ApplicationController看起来如何?
在logged_in?
开始工作之前,您需要将其包含为helper_method
。这样的东西,在ApplicationController中:
class ApplicationController < ActionController::Base
include SessionsHelper
helper_method :logged_in?
end
答案 1 :(得分:0)
在current_user
模块的SessionsHelper
方法中,使用以下代码
if (user_id == session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id == cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
您已使用=
运算符进行比较而不是==
。