lundi 23 octobre 2017

How to adjust Controller so ordering the table by prename works in ruby on rails

Rails noob here. I would like to know why the order function does not work when you not searched for a person using the search function. The user can click on the table head prename and the table should be ordered asc or desc. There is also a search function on this page. When you search for a person and there are like 1+ results, here the ordering works. But it does not work when you have not searched for a person.

Tables

  • person has_many :participants
  • participant belongs_to person

When you visit the page the persons are ordered by the frequency of the participants.

PersonsController

if params[:search_me]
     @persons = Person.search_me(params[:search_me]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 5, :page => params[:page])
else
 @persons = Person.select('persons.*, count(participants.person_id) AS participant_count').joins(:participants).group('participants.person_id').order('participant_count desc').paginate(:per_page => 30, :page => params[:page]).order(sort_column + ' ' + sort_direction)
end

private

def sort_column
   Person.column_names.include?(params[:sort]) ? params[:sort] : "prename"
end

def sort_direction
   %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end

Person View

<%= will_paginate @persons, :previous_label => t("previous_label"), :next_label => t("next_label"), :page_gap => t("will_paginate.page_gap")%>

Thank you in advance

Aucun commentaire:

Enregistrer un commentaire