Lecture Notes for CS349W
Fall Quarter 2008
John Ousterhout
class CreateStudents < ActiveRecord::Migration def self.up create_table :students do |t| t.column :last, :string t.column :first, :string t.column :gpa, :float end end def self.down drop_table :students end end
class AddEmail < ActiveRecord::Migration def self.up add_column :students, :email, :string end def self.down remove_column :students, :email end end
ruby script/generate model studentCreates file models/student.rb:
Class Student < ActiveRecord::Base end
student = Student.new student.name = "Smith" student.email = "smith@cs.stanford.edu" student.gpa = 3.21 student.save
student = Student.find(21463) student = Student.find_by_name("Smith")
smarties = Student.find (:all, :conditions => "gpa >= 3.0"); smarties = Student.find(:all, :limit => 10, :order => "gpa DESC");
student = Student.find(21463) student.gpa = 4.0 student.save
Student.find(21463).destroy
class Student < ActiveRecord::Base belongs_to :advisor ... end class Advisor < ActiveRecord::Base has_many :students ... end
ouster = Advisor.find_by_name("Ousterhout") students = ouster.students() Student student = Student.find_by_name("Smith") student.advisor = ouster student.save
class Student < ActiveRecord::Base has_and_belongs_to_many :courses ... end class Course < ActiveRecord::Base has_and_belongs_to_many :students ... end
smith = Student.find_by_name("Smith") smith_courses = smith.courses() cs142 = Course.find_by_name("CS142") smith_courses << cs142