您能否将 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。谢谢!

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

相关内容

最新更新