diff --git a/app/controllers/studies_controller.rb b/app/controllers/studies_controller.rb index ff32701..f0e716a 100644 --- a/app/controllers/studies_controller.rb +++ b/app/controllers/studies_controller.rb @@ -1,7 +1,8 @@ class StudiesController < ApplicationController + helper_method :sort_column, :sort_direction def index - @studies = Study.all + @studies = Study.order(sort_column + " " + sort_direction) end def show @@ -35,4 +36,12 @@ def study_params params.require(:study).permit(:title, :principal_investigator, :open) end + def sort_column + Study.column_names.include?(params[:sort]) ? params[:sort] : "title" + end + + def sort_direction + %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" + end + end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index de6be79..340215b 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,2 +1,9 @@ module ApplicationHelper + + def sort_by_column(column, title = nil) + title ||= column.titleize + direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc" + link_to title, {:sort => column, :direction => direction} + end + end diff --git a/app/views/studies/index.html.erb b/app/views/studies/index.html.erb index c02be99..6bf65d2 100644 --- a/app/views/studies/index.html.erb +++ b/app/views/studies/index.html.erb @@ -3,10 +3,10 @@
| Study Number | -Title | -Principal Investigator | -Status | +<%= sort_by_column "id", "Study Number" %> | +<%= sort_by_column "title" %> | +<%= sort_by_column "principal_investigator", "Principal Investigator" %> | +<%= sort_by_column "open", "Status"%> |
|---|