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 belongs_to :deparment end class Department < ActiveRecord::Base has_many :doctors end
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 :
Select your Doctor:
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 :
def index @doctors = Department.find(:all, :order => 'name') end in doctors/ index.html.erb:
Now our patient can easily find any doctor in the dropdown as well as in the doctors list.