ruby-on-rails - 用户如何在 Rails 中只查看自己的帖子?
问题描述
我只从帖子中随机显示一个帖子。
但我只想显示我发布的帖子,而不是整个帖子。(使用设计。)
我应该使用 cancancan 和 rolify gem 吗?
我想知道如何在不使用它的情况下做到这一点。
职位控制器
def index
@posts = Post.order("RANDOM()").first(1)
end
index.html.erb
<% @posts.each do |x| %>
<div class="xxx">
<div class="boxcolor">
<div class="boxcolor2" style="background-color:<%=x.color%>;"></div>
</div>
<div class="boxtit"><%=x.title%></div>
<div class="boxcon"><%=x.content%></div>
</div>
<% end %>
解决方案
否则在控制器中使用它,它会在找不到当前用户 ID 时显示错误
before_action :authenticate_user!
并像这样进入索引操作
@posts = current_user.posts.order("RANDOM()").first(1)
推荐阅读
- db2 - DB2 ODBC:来自未失败的查询的“HY010 函数序列错误”
- firebase - 如果 App 组件未卸载,如何在 useEffect 挂钩清理功能中分离 Firebase 侦听器
- excel - 范围内的 Excel 宏迭代
- unity3d - Unity 枪不能顺利跟随相机
- python - 如何让 Visual Studio 代码为代码完成/智能感知提出类属性?
- c# - 任何项目在代码中发布但发生错误。我该如何解决?
- wpf - Datatable.DefaultView.RowFilter 对某些用户不起作用
- javascript - 如何在 Puppeteer 中构建背靠背 Promise.all 请求
- r - 是否有必要关闭在函数中打开的文件?
- variables - 如何为计算多项式创建类或元表