简体   繁体   English

Ruby on rails - 在创建 session 并重定向主页后用户为零

[英]Ruby on rails - user is nil after creating a session and redirecting home

I am building a rails app.我正在构建一个 Rails 应用程序。

  • I am using devise to handle authentication我正在使用 devise 来处理身份验证
  • If the user is an admin, he or she should be able to see a link in the navbar that redirects to the whole list of profiles (for testing purposes)如果用户是管理员,他或她应该能够在导航栏中看到一个链接,该链接重定向到整个配置文件列表(用于测试目的)
    <% if !user_signed_in? %>
        <li class="nav-item">
          <%= link_to "Sign up", new_user_registration_path, class: "nav-link" %>
        </li>
        <li class="nav-item">
          <%= link_to "Log in", new_user_session_path, class: "nav-link" %>
        </li>
      <% else %>
        <li class="nav-item">
          <%= link_to "Log out", destroy_user_session_path, method: :delete,  class: "nav-link" %>
        </li>
        <% if !@user.nil? && @user.admin? %>
          <li class="nav-item">
            <%= link_to "See all profiles", profiles_path, class: "nav-link" %>
          </li>
        <% end %>
        <li class="nav-item">
          <%= link_to "My profile", user_profile_path(current_user, current_user.user_profile), class: "nav-link" %>
        </li>
    <% end %>
  • However, said link only shows after going inside the my profile link.但是,该链接仅在进入my profile链接后才会显示。 I did a raise in the UserProfiles controller to see what's going on and apparently the user is nil in the homepage even after logging in, hence the reason why the see all profiles link is not appearing我在 UserProfiles controller 中进行了加注,以查看发生了什么,显然即使在登录后user在主页上也为零,因此查看所有配置文件链接没有出现的原因

  • My guess is that I am missing an instance variable that provides the user id somewhere, (pages controller perhaps?) I don't have a users controller or user sessions controller yet.我的猜测是我缺少一个在某处提供用户 ID 的实例变量,(也许是页面 controller?)我还没有用户 controller 或用户会话 Z594C103F2C6E04C3D8AB059F031E。 Basically, I don't understand why is the user nil after logging in and why is the log out link showing up without a user?基本上,我不明白为什么登录后用户为零,为什么在没有用户的情况下显示注销链接?

UserProfiles controller用户配置文件 controller

class UserProfilesController < ApplicationController
  before_action :set_user, only: [:index, :show]
  
  def index
    @user_profiles = UserProfile.all
  end

  def show
    @user_profile = UserProfile.find(params[:id])
    @user_profile.user = @user
  end
  
  private
  
  def set_user
    @user = current_user
  end
end

Thanks for your help谢谢你的帮助

You are not passing @user from the controller so cannot use in the view .您没有从controller @user不能在view中使用。

You should change your code to您应该将代码更改为

<% if !@user_profile.user.nil? && @user_profile.user.admin? %>
   <li class="nav-item">
      <%= link_to "See all profiles", profiles_path, class: "nav-link" %>
    </li>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM