You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rails文章详情页显示同分类相关文章的实现方法

嘿,这个需求其实很容易实现,咱们利用已经建好的关联关系就能搞定,分两步走就行:

实现同分类相关文章展示的步骤

1. 修改PostsController的show方法

首先你需要在posts_controller.rb的show动作里,获取当前文章所属分类下的其他文章(要排除当前文章本身哦,不然会把自己也列进去)。

假设你原来的show方法是这样的:

def show
  @post = Post.friendly.find(params[:id]) # 如果你也用了friendly_id的话,不然就是Post.find(params[:id])
end

那现在修改成:

def show
  @post = Post.friendly.find(params[:id])
  # 获取同分类下的相关文章,排除当前文章
  @related_posts = @post.category.posts.where.not(id: @post.id)
  # 可选:可以加个排序,比如按创建时间倒序
  # @related_posts = @post.category.posts.where.not(id: @post.id).order(created_at: :desc)
end

这里利用了你已经建立的belongs_to关联,@post.category直接就能拿到当前文章的分类,再调用.posts就得到该分类下的所有文章,然后用where.not(id: @post.id)把当前文章排除掉,非常简洁。

2. 在文章详情页视图中渲染相关文章

接下来在app/views/posts/show.html.erb(或者你对应的视图文件)的合适位置(比如文章内容的底部),添加相关文章的列表:

<h3>相关文章</h3>
<% if @related_posts.present? %>
  <ul>
    <% @related_posts.each do |post| %>
      <li><%= link_to post.title, post %></li>
    <% end %>
  </ul>
<% else %>
  <p>暂无相关文章</p>
<% end %>

这样就搞定啦!用户访问文章详情页的时候,就能看到同一分类下的其他文章列表了。

另外补充一点:如果你的Category模型有all的获取需求,比如侧边栏显示所有分类,那可以把@categories = Category.all放到ApplicationController的before_action里,这样所有页面都能直接用,不用在categories和posts的控制器里重复写了,代码更简洁。

内容的提问来源于stack exchange,提问作者Charlie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:39:19