按#问题排序评论

时间:2013-12-29 00:57:41

标签: ruby-on-rails ruby-on-rails-4

我有3个模型:帖子,评论和问题(注意:问题属于评论)。我想按每个帖子的评论数量对每个帖子的问题进行排序。我有一个评论部分,由我的帖子显示页面调用,显示所有评论。

帖子显示:

<%= render :partial => @post.comments %>

评论部分:

<%= div_for(comment) do %>

和帖子控制器:

def show
@post = Post.find(params[:id])
@comments = Post.order("created_at desc")
end

1 个答案:

答案 0 :(得分:1)

在评论表中添加一个计数器,以记录它有多少问题。

迁移文件

class AddQuestionsCountToComments < ActiveRecord::Migration
  def change
    add_column :commments, :questions_count, :integer, :default => 0
  end
end

模型文件

class Comment
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :comment, :counter_cache => true
end

发布秀

<%= render :partial => @post.comments.order('comments.questions_count desc') %>
相关问题