Reputation: 289
I need help figuring out how to sort my posts by the number of comments they have. Whenever multiple posts have the same number of comments, it will sort by most recent. I'm also trying to figure out if I should do this in the model or the controller.
post.rb
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :user
end
posts_controller.rb
class PostsController < ApplicationController
def index
@feed = Post.find(:all, :order => "created_at ASC")
@posts = Post.includes(:comments).order("comments.size ASC, created_at DESC").page(params[:page]).per(1)
end
I'm using the kaminari gem for paging. I'll provide anything else that will help to answer this question.
Upvotes: 1
Views: 1823
Reputation: 289
Thanks in part to Dave Newton for providing a resource for me to work off of. I added the counter cache to keep a running count of the total amount of columns each post has. This is working so far.
comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true, :counter_cache => true
belongs_to :user
end
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.order("comments_count, created_at DESC").page(params[:page]).per(1)
end
end
migration
class AddCommentCounter < ActiveRecord::Migration
def self.up
add_column :posts, :comments_count, :integer, :null => false, :default => 0
Post.reset_column_information
Post.all.each do |p|
p.update_attribute :comments_count, p.comments.length
end
end
def self.down
remove_column :posts, :comments_count
end
end
This is working for me so far to sort by total comments and then by most recently created. Here is the railscasts link: railscasts.com/episodes/23-counter-cache-column.
Upvotes: 2