Rails教程第8课当前用户无法正常工作?

时间:2015-09-07 12:07:50

标签: ruby-on-rails

嘿,所有人都陷入了导弹教程Michael Hartl的第8课我记录了吗?函数似乎没有工作,因为我的导航栏没有显示登录的列表项,而是显示相反的情况,也没有指向配置文件工作的链接

这是我的代码。非常感谢任何帮助

application.html.erb

<header class = "navbar navbar-fixed-top navbar-inverse">
    <div class = "container">
        <%= link_to "sample app", home_path, id: "logo" %>
        <ul class = "nav navbar-nav navbar-right">

 <% if logged_in? %>
                <li> <%= link_to "Home", home_path %> </li>
                <li> <%= link_to "About", about_path %> </li>
                <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 "Home", home_path %> </li>
                <li> <%= link_to "About", about_path %> </li>
                <li><%= link_to "Profile", current_user %></li>
                <li><%= link_to "Log in", login_path %></li>
            <% end %>

sessionshelper.rb

  module SessionsHelper
    def log_in(user)
        session[:user_id] = user.id
    end

    def current_user
        @current_user ||= User.find_by(id: session[:user_id])
    end

    # returns true if the user is logged in

    def logged_in?
        !current_user.nil?
    end

  end

1 个答案:

答案 0 :(得分:0)

尝试使用长格式替换def current_user中的代码 -

if @current_user.nil?
  @current_user = User.find_by(id: session[:user_id])
else
  @current_user
end

并测试它是否有效

def current_user

    if @current_user.nil?
      @current_user = User.find_by(id: session[:user_id])
    else
      @current_user
    end

end