【问题标题】:Rails display Related or Similar posts from category on the post show pageRails 在帖子显示页面上显示类别中的相关或相似帖子
【发布时间】:2018-04-07 04:49:53
【问题描述】:

我有 Postcategory 模型

Post
belongs_to :category

Category
has_many :posts

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

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

categories_controller ....

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

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

【问题讨论】:

  • Category.friendly.includes(:posts) 将获取与友好类别相关的所有帖子
  • @praga2050 显示页面上使用的语法有什么更新吗?您的方法有效,但只是循环同一个帖子而不显示相关内容。谢谢

标签: ruby-on-rails ruby related-content


【解决方案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)

【讨论】:

  • 感谢您的反馈。您能否分享在帖子显示页面上使用的语法来获取相关帖子?我试过 .... 和 ... 但两者都在自己的页面上显示同一帖子的列表,而不是获取相关帖子
  • 查理,你查看过数据库吗?除了当前的,还有需要category_id的帖子吗?
  • 是的,我已经在 Rails 控制台中签入,所有帖子都有 category_id。具有相同 category_id 的帖子列表也可以在特定类别页面上正常显示
【解决方案2】:

无需使用 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 %> 

或者你可以通过将每个循环修改为&lt;% @post.category.posts.each do |post| %&gt;来避免@related_posts变量

希望这会对你有所帮助。

【讨论】:

  • 感谢@Ganesh,这在posts_controller 中是有意义的。在帖子显示页面上使用什么完整语法来获取相关帖子?
  • 使用上述方法仍然会在多个相关帖子中显示相同的帖子,但不会显示实际的相关帖子。顺便说一句,我一直使用“related_posts”而不是与“relative_posts”混合使用
  • 我正在尝试将这个逻辑放在posts_controller @posts = Post.where.not(id: @post.id).belongs_to_category(@post.category.post, any: true) 我知道.belongs_to_category 不是一个正确的语法,但知道我该怎么做吗?
  • 此查询@posts = @category.posts.where.not(id: @post.id) 可能会对您有所帮助。
  • 感谢大家的帮助。它仍然在多个相关帖子中显示相同的帖子。可能是我的数据库有问题。我会玩弄它以找出答案。
【解决方案3】:

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

控制器应该是:

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

展示后视图:

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

感谢大家的贡献

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多