Reputation: 553
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
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