ruby-on-rails - 如何检查 Rails 5 中相同 post_author 发布的帖子?
问题描述
所以我在我的视图中有这段代码(show.html.erb)来检查和显示同一作者发布的帖子:
<% @posts.each do |post| %>
<!-- Check for same post author -->
<p><%= @post.title %></p>
<!-- End check -->
<% end %>
这是我的控制器:
def show
@posts = Posts.all.order("created_at desc")
end
我试过@sameauthor = Posts.where(post_author: params[:post_author]).order("created_at desc")
更新。
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :post_author)
end
end
解决方案
你的答案是:
def show
@posts_by_same_author = Post.where('post_author = ?', @post.post_author).order("created_at desc")
end
它会为您提供由当前帖子 ( @post
) 作者撰写的帖子。然后在视图中遍历这个实例变量:
<% @posts_by_same_author.each do |post| %>
<p><%= post.title %></p>
<p><%= post.post_author %></p>
<% end %>
推荐阅读
- angular - Angular - 如何将数组参数路由到新的模态组件
- mysql - mysql select for update 是如何工作的
- flutter - 找不到正确的提供者
在此 SignUpIdols 小部件上方 - flutter - Flutter dart 将 hive 保存的数据导出到文件以供以后检索
- laravel - Laravel JWT Auth Invalidate token - 一次允许一个设备
- css - 如何将两列合并为一行(wordpress)?
- jpa - 如果发生异常,则回滚所有插入
- javascript - 创建实例时的异步操作
- c# - 如何在 Dot net core 项目中添加 COM 引用
- android - 图片按钮不显示图片本身