在铁路中使用注释进行排序的帖子

时间:2018-07-12 16:51:49

标签: ruby-on-rails

我想根据评论数显示评论,因为我想修改@posts以按评论数排序,非常感谢 发布模型

has_many :comments

帖子控制器

@posts = Post.all

评论模型:

belongs_to :post 

评论控制器

@post = Post.find(params[:id])
@comment = @post.comments.order("CREATED_AT DESC")

1 个答案:

答案 0 :(得分:0)

Rails提供了counter_cache的帮助。您可以阅读有关here

的信息

有两个步骤

  1. 在您的帖子表中添加comments_cout列

rails g migration AddCommentsCountToPosts comments_count:integer

rake db:migrate

  1. 将counter_cache选项添加到注释belongs_to关系中

class Comment < ApplicationRecord belongs_to :post, counter_cache: true end

class Post < ApplicationRecord has_many :comments end

然后您可以按PostsController index动作中的comments_count排序

@posts = Post.order(:comments_count)

相关问题