首页 > 解决方案 > 您能否将 Rails 中的 link_to 元素限制为仅在您以管理员身份登录时才可见?

问题描述

所以我正在尝试在 Rails 中创建一个新的投资组合站点,并且我正在尝试解决它的管理组件。具体来说,有一个博客功能,我想成为唯一可以查看新/编辑/删除/等的人。博客本身的功能。如果某人没有以管理员身份登录,我希望他们看到相同的页面而无法查看这些选项的链接。

现在,视图如下所示:

<div class="content has-text-centered">
  <h1 class="title">Blog</h1>
</div>

<section class="section">
  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
      </tr>
    <% end %>
   </tbody>
</table>
<br>
</section>

<%= link_to 'New Post', new_post_path %>

...而且我基本上试图让它在页面本身上只有前三行可见,除非用户以管理员身份登录。

关于如何处理这个问题的任何建议?我正在使用 Ruby 2.4.1、Rails 5.2.0 和 Devise 4.4.3。谢谢!

标签: ruby-on-railsauthenticationdeviseadminerb

解决方案


使用 user_signed_in?方法,并且仅在返回 true 时显示该块:

<div class="content has-text-centered">
  <h1 class="title">Blog</h1>
</div>

<% if user_signed_in? %>
  <section class="section">
    <tbody>
      <% @posts.each do |post| %>
        <tr>
          <td><%= link_to 'Show', post %></td>
          <td><%= link_to 'Edit', edit_post_path(post) %></td>
        </tr>
      <% end %>
     </tbody>
  </table>
  <br>
  </section>
<% end %>

这是假设您的设计用户模型是“用户”。如果它是“管理员”,那么它将是

<% if admin_signed_in? %>

有关更多信息,请参阅https://github.com/plataformatec/devise/wiki/How-To:-Add-sign_in,-sign_out,-and-sign_up-links-to-your-layout-template


推荐阅读