Rails 5 查询从我当前查看的帖子以外的同一类别中提取帖子 [英] Rails 5 Query to pull posts from same category other than the post I'm currently viewing

查看:55
本文介绍了Rails 5 查询从我当前查看的帖子以外的同一类别中提取帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在帖子详细信息页面显示来自同一类别的其他 3 个帖子.所以我有这个查询:

I'm trying to display 3 other posts from same category at post details page. So I have this query:

  def show
    @posts_from_same_category = Post.where(category_id: @post.category_id).limit(3).order("RANDOM()")
  end

所以页面结构是这样的:

So the page structure is like:

  • 帖子标题
  • 帖子文本
  • (title) 来自同一类别的更多帖子
  • 其他帖子标题 1
  • 其他帖子标题 2
  • 其他帖子标题 3

它返回所有帖子,包括我正在查看的帖子.如何编写查询以提取当前正在查看的帖子以外的帖子?

It returns all posts including the posts I'm viewing. How can I write the query to pull posts other than the one I'm currently viewing?

谢谢

推荐答案

您可以添加另一个条件来排除当前帖子:

You could add another condition to exclude current post:

@other_posts = @post.category.posts.where.not(id: @post.id).limit(3).order('RANDOM()')

这篇关于Rails 5 查询从我当前查看的帖子以外的同一类别中提取帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆