如何检查Rails 5中同一post_author发布的帖子?

问题描述 投票:0回答:1

所以我在我的视图(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
1个回答
0
投票

你的答案是:

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 %>
© www.soinside.com 2019 - 2024. All rights reserved.