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



我正在构建一个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的实例变量,(也许是页面控制器?(我还没有用户控制器或用户会话控制器。基本上,我不明白为什么登录后用户为零,为什么注销链接显示时没有用户?

UserProfiles控制器

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

感谢您的帮助

您没有从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 %>

最新更新