1

我有Postcategory模型

Post
belongs_to :category

Category
has_many :posts

在类别显示页面上,我可以通过以下方式显示属于该类别的所有帖子的列表

<% Post.where(category_id: @category.id).each do |post| %>
....
<% end %>

类别控制器 ....

def show
    @category = Category.friendly.find(params[:id])
    @categories = Category.all 
end

如何在帖子的显示页面之一上显示属于同一类别(或共享相同类别 ID)的相关帖子列表。谢谢!

4

3 回答 3

1

无需使用 where 条件,因为您已经在 Post 和 Category 之间建立了关联。所以你可以修改以下代码

Post.where(category_id: @category.id)

作为

@category.posts

所以你的表演动作posts_controller.rb应该是这样的

def show
  @post = Post.find(params[:id])
  @relative_posts = @post.category.posts
end

现在您的视图应该类似于

<% @related_posts.each do |post| %>
   // disply details of individual post 
<% end %> 

或者您可以@related_posts通过将每个循环修改为 <% @post.category.posts.each do |post| %>

希望这会帮助你。

于 2018-04-07T07:19:13.327 回答
1

我假设您可以在以下位置执行以下操作posts_controller

def show
  @post = Post.find(params[:id])

  @relative_posts = Post.where(category_id: @post.category_id)
end

顺便说一句,一个好的做法是使用范围而不是where

Post
belongs_to :category
scope :of_category, ->(category) { where(category_id: category) }

这样在控制器中你可以做

@relative_posts = Post.of_category(@post.category)
于 2018-04-07T05:41:22.210 回答
0

我的错,我一直在显示视图中调用“@post”而不是“post”

控制器应该是:

@related_posts = Post.where(category_id: @post.category_id)

展后视图:

<% @related_posts.each do |post| %>
<%= post.name %>
<% end %>

感谢大家的贡献

于 2018-04-16T07:20:50.747 回答