【问题标题】:Ruby on rails - user is nil after creating a session and redirecting homeRuby on rails - 创建会话并重定向主页后用户为零
【发布时间】:2021-05-13 23:36:19
【问题描述】:

我正在构建一个 Rails 应用程序。

  • 我正在使用设计来处理身份验证
  • 如果用户是管理员,他或她应该能够在导航栏中看到一个链接,该链接重定向到整个配置文件列表(用于测试目的)
    <% 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 %>
  • 但是,该链接仅在进入my profile 链接后才会显示。我在 UserProfiles 控制器中进行了提升以查看发生了什么,显然 user 在登录后在主页中为零,因此查看所有配置文件链接没有出现

  • 我的猜测是我缺少一个在某处提供用户 ID 的实例变量(可能是页面控制器?)我还没有用户控制器或用户会话控制器。基本上,我不明白为什么用户登录后为零,为什么在没有用户的情况下显示退出链接?

用户配置文件控制器

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

感谢您的帮助

【问题讨论】:

  • 你检查!user_signed_in? -> 没有签入,那你的问题,应该是`if user_signed_in?`
  • 您好,谢谢您的回复。 !user_signed_in? 用于拍摄登录和注册链接。登录用户的逻辑在 else 之后。问题是当我回到家时,see all profiles 消失了,因为没有用户。
  • 我想我现在知道你的问题了,你上面的 erb 文件属于 HomeControlle 而不是 UserProfilesController,对吧?你应该同时使用current_user,不应该设置@user = current_user,因为@user on UserProfilesController 将在 HomeController 上为零,同时current_user 将在用户登录后设置每个控制器。
  • 我发现了问题所在,我将user_profile 路由嵌套在用户路由中。一旦我将它们分开,一切都很好。感谢您的帮助。

标签: ruby-on-rails devise


【解决方案1】:

您没有从controller 传递@user,因此不能在view 中使用。

您应该将代码更改为

<% 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 %>

【讨论】:

  • 嘿,卡马尔。感谢您的回复,不幸的是它没有用,我仍然是零。用户和 user_profile 在主视图中均不可用。我会继续寻找,如果我弄明白了会告诉你的。
  • 你能显示user modeluser_profile model吗?
  • 我发现了问题所在,我将user_profile 路由嵌套在用户路由中。一旦我将它们分开,一切都很好。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
相关资源
最近更新 更多