【发布时间】: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