Rewrite sorting to support direction param [#2931]

This commit is contained in:
Anna Anks Nowak
2019-01-01 01:11:36 +01:00
committed by Javi Martín
parent 2877229904
commit 9786b0bf7d
4 changed files with 18 additions and 7 deletions

View File

@@ -227,6 +227,7 @@ $sidebar-active: #f4fcd0;
a {
color: inherit;
white-space: nowrap;
}
}

View File

@@ -77,7 +77,8 @@ class Admin::BudgetInvestmentsController < Admin::BaseController
def load_investments
@investments = Budget::Investment.scoped_filter(params, @current_filter)
.order_filter(params[:sort_by])
.order_filter(params[:sort_by], params[:direction])
@investments = @investments.page(params[:page]) unless request.format.csv?
end

View File

@@ -5,9 +5,15 @@ module BudgetInvestmentsHelper
def link_to_investments_sorted_by(column)
sorting_option = column.downcase
direction = sorting_option && params[:direction] == "asc" ? "desc" : "asc"
icon = direction == "asc" ? "icon-arrow-top" : "icon-arrow-down"
icon = sorting_option == params[:sort_by] ? icon : ""
translation = t("admin.budget_investments.index.sort_by.#{sorting_option}")
link_to(
t("admin.budget_investments.index.sort_by.#{sorting_option}"),
admin_budget_budget_investments_path(sort_by: sorting_option)
"#{translation} <span class=\"#{icon}\"></span>".html_safe,
admin_budget_budget_investments_path(sort_by: sorting_option, direction: direction)
)
end

View File

@@ -1,6 +1,6 @@
class Budget
class Investment < ActiveRecord::Base
SORTING_OPTIONS = %w(id title supports).freeze
SORTING_OPTIONS = [{"id": "id"}, {"title": "title"}, {"supports": "cached_votes_up"}].freeze
include Rails.application.routes.url_helpers
include Measurable
@@ -139,9 +139,12 @@ class Budget
results.where("budget_investments.id IN (?)", ids)
end
def self.order_filter(sorting_param)
if sorting_param.present? && SORTING_OPTIONS.include?(sorting_param)
send("sort_by_#{sorting_param}")
def self.order_filter(sorting_param, direction)
sorting_key = sorting_param.to_sym
available_option = SORTING_OPTIONS.select { |sp| sp[sorting_key]}.reduce
if sorting_param.present? && available_option.present? then
%w[asc desc].include?(direction) ? direction : "desc"
order("#{available_option[sorting_key]} #{direction}")
else
order(cached_votes_up: :desc).order(id: :desc)
end