user2759575
user2759575

Reputation: 553

Sorting comments by # of questions

I have 3 models: posts, comments and questions (note: questions belong to comments). I would like to sort each posts questions by the number of comments they each have. I have a comments partial that is called by my posts show page that shows all the comments.

Posts show:

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

Comments partial:

<%= div_for(comment) do %>

and the posts controller:

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

Upvotes: 0

Views: 44

Answers (1)

nickcen
nickcen

Reputation: 1692

add a counter inside the commments table to record how many questions it have.

the migration file

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

the model files

class Comment
  has_many :questions
end

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

Post show

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

Upvotes: 1

Related Questions