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

时间:2018-08-26 01:54:09

标签: ruby-on-rails authentication devise admin erb

因此,我试图在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。谢谢!

1 个答案:

答案 0 :(得分:3)

使用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