Ruby on Rails等问题

Tre*_*lof 8 ruby ruby-on-rails

我有一个应用程序,在布局中我有一个user_name div,根据他们是否登录显示不同的东西,是管理员等.现在我的代码如下:

  <% if current_user.role == "admin" %>
  <p id="admintxt">You are an admin!</p>
      <%= link_to "Edit Profile", edit_user_path(:current) %>
   <%= link_to "Logout", logout_path %>
  <% elsif current_user %>
   <%= link_to "Edit Profile", edit_user_path(:current) %>
   <%= link_to "Logout", logout_path %>
  <% else %>
<%= link_to "Register", new_user_path %>
<%= link_to "Login", login_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

我已经有一个current_user帮助器,当代码只是时,一切正常:

<% if current_user %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
    <%= link_to "Register", new_user_path %>
    <%= link_to "Login", login_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

现在,当我将其作为elsif语句时,当我以管理员身份登录时,它可以工作,并且我会使用正确的链接显示文本.当我不是管理员用户/注销时,我得到nil的未定义方法`role':NilClass错误...我的current_user内容在我的应用程序控制器中声明如下:

helper_method :current_user


private

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end
Run Code Online (Sandbox Code Playgroud)

有什么想法,我可以做什么来显示我想要的结果?"如果他们是角色属性等于admin的用户,他们会获得一些文本和登录链接,如果他们只是一个用户,他们就会获得登录链接,如果他们没有登录,他们会获得注册和登录链接.

谢谢!

Sim*_*tti 12

<% if current_user %>
  <% if current_user.role == "admin" %>
    <p id="admintxt">You are an admin!</p>
    <%= link_to "Edit Profile", edit_user_path(:current) %>
    <%= link_to "Logout", logout_path %>
  <% else %>
    <%= link_to "Edit Profile", edit_user_path(:current) %>
    <%= link_to "Logout", logout_path %>
  <% end %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

或者使用Rails> = 2.3

<% if current_user.try(:role) == "admin" %>
  <p id="admintxt">You are an admin!</p>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% elsif current_user %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

隐藏当前用户循环中的角色检查,这会产生简化条件的副作用.

<% if current_user %>
  <%= content_tag(:p, "You are an admin!", :id=>"admintxt") if current_user.role == "admin" %>
  <%= link_to "Edit Profile", edit_user_path(:current) %>
  <%= link_to "Logout", logout_path %>
<% else %>
  <%= link_to "Register", new_user_path %>
  <%= link_to "Login", login_path %>
<% end %>
Run Code Online (Sandbox Code Playgroud)