diff --git a/app/controllers/communities_controller.rb b/app/controllers/communities_controller.rb index b8d691aa7..f28e03a05 100644 --- a/app/controllers/communities_controller.rb +++ b/app/controllers/communities_controller.rb @@ -1,6 +1,8 @@ class CommunitiesController < ApplicationController - before_action :set_community, :load_topics, only: :show + before_action :set_order, :set_community, :load_topics, only: :show + + has_orders %w{newest most_commented oldest}, only: :show skip_authorization_check @@ -9,11 +11,15 @@ class CommunitiesController < ApplicationController private + def set_order + @order = params[:order].present? ? params[:order] : "newest" + end + def set_community @community = Community.find(params[:id]) end def load_topics - @topics = @community.topics.page(params[:page]) + @topics = @community.topics.send("sort_by_#{@order}").page(params[:page]) end end diff --git a/app/models/topic.rb b/app/models/topic.rb index 6da411aab..4161a4dce 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -9,6 +9,10 @@ class Topic < ActiveRecord::Base after_create :associate_comment + scope :sort_by_newest, -> { order(created_at: :desc) } + scope :sort_by_oldest, -> { order(created_at: :asc) } + scope :sort_by_most_commented, -> { reorder(comments_count: :desc) } + private def associate_comment diff --git a/app/views/topics/_topics.html.erb b/app/views/topics/_topics.html.erb index 0e6709daf..48b878bec 100644 --- a/app/views/topics/_topics.html.erb +++ b/app/views/topics/_topics.html.erb @@ -1,22 +1,6 @@ -