首页 > 解决方案 > 如何检查 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

标签: ruby-on-rails

解决方案


你的答案是:

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 %>

推荐阅读