您能否将 Rails 中的 link_to 元素限制为仅在您以管理员身份登录时可见?

Can you restrict a link_to element in Rails to only be visible if you're logged in as an admin?

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

现在,视图如下所示:

<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。谢谢!

使用user_signed_in?方法,并且仅在 returns 为真时才显示该块:

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

这是假设您的设计用户模型是 'User'。如果它是 'Admin' 那么它将是

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