ruby-on-rails - 您能否将 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? %>
推荐阅读
- javascript - 如何在 Nodejs 和 graphql-upload 中传输多个流以将文件/流上传到 Cloudinary 或其他存储提供商?
- algorithm - 查找给定字符串的所有前缀的最长回文子串的长度
- decomposition - 将最小覆盖转换为 3NF
- apache-spark - 在火花中清理 JSON 对象?
- sql - 如何找到 mongodb 模式的方法?
- python - Python Selenium execute_script("return window.dataLayer") 返回过时的引用?什么是陈旧的?一切都还在
- algorithm - 在 O(1) 空间中的数组中找到重复元素的证明
- common-lisp - 哈希表的自定义打印机
- javascript - 想要使用js创建div的内部部分
- ruby-on-rails - “rake routes”导致语法错误:time_zone.rb 循环参数参考 - 现在