To Lecture Notes
Some ActiveRecord Examples
- Sometimes you want to display only some of the information
in a database.
- Try out the following ActiveRecord method calls in
Example 26 (DisplayGradeData Example). Replace the controller line
@a = GradeRecord.all
a line similar to one of the following.
# Find all of the rows in the database. Long version of previous line:
@a =GradeRecord.find(:all)
# Find first student in database. A GradeRecord object is returned.
@a = GradeRecord.find(:first)
@a = GradeRecord.first
# Find last student in database. A GradeRecord object is returned.
@a = GradeRecord.find(:last)
@s = GradeRecord.last
Here are some various finds with conditions. You can use :first or
:last instead of :all if you wish:
# Find all grade records with credit_hours >= 2.
@a = GradeRecord.find(:all, :conditions => 'credit_hours >= 2')
# Find the student with stud_id == 3423.
@a = GradeRecord.find(:all, :condition => 'stud_id = 3423')
# Shortcut for previous statement.
@a = GradeRecord.where(:stud_id => 3423)
# Previous statement using a dynamic finder.
@a = GradeRecord.find_all_by_stud_id(3423)
# Sort by grade.
@a = GradeRecord.find(:all, :order => 'grade')
# Sort by descending grade.
@a = GradeRecord.find(:all, :order => 'gpa desc')
# Sort by gpa, with secondary sort on student_id.
# Sorting by student_id only matters when there is a tie for gpa.
@a = GradeRecord.find(:all, :order => 'stud_id, grade')
You can include both :conditions and :order within the same
find statement.
See Example 26 (DisplayGradeData Example).