Generally when we fetch records from our DB and render those in our view without caring about sorting those records.
Let’s consider a case, we have doctors name in a dropdown and patient needs to chose one doctor whose name is “James Brito”. If we have 1000 doctor names then it’ll be quite tough for our patient to find his/her favorite doctor in the list.
For better user experience those records should be sorted in view level.
Let’s take this sample case :
class Doctor < ActiveRecord::Base
class Department < ActiveRecord::Base
Keep the values sorted in Drop down list :
Now represent those to End User (keeping doctor names in a dropdown ) performing sorting on name Column (as our patient can search James Brito Alphabetically) sorting values in View Page :
<strong> Select your Doctor: </strong>
<%= collection_select(:department, :doctor_id, Doctor.order('name ASC'), :id, :name) %>
Keep the values sorted in index View:
Let’s say We want to Doctor names should be alphabetically sorted in index page :
We need to sort it at the controller level ; then render the same in View.
Sorting the values in controller Section :
@doctors = Department.find(:all, :order => 'name')
in doctors/ index.html.erb:
<% @doctors.each do |doctor| %>
<%= doctor.name %>
<% end %>
Now our patient can easily find any doctor in the dropdown as well as in the doctors list.