Examples: # Create Examples # create a teacher t = Teacher.new(first_name: 'rahul', last_name: 'garg', email: '[email protected]') t.save # count of teachers Teacher.count # create in one line t = Teacher.create(first_name: 'some', last_name: 'thing', email: '[email protected]') # Read and Find examples # find first record by email t = Teacher.where(email: '[email protected]').first # first record of the table t = Teacher.first # last record of the table t = Teacher.last # find by id t = Teacher.find(id) e.g. Teacher.find(3) # fetch all teachers teachers = Teacher.all # fetch all teachers with order created_at desc teachers = Teacher.order('created_at desc') teachers = Teacher.limit(2) teachers = Teacher.limit(2).order('created_at desc') # Update Examples # udpate example using "save" teacher = Teacher.first teacher.email = "[email protected]" teacher.save teacher.email = "[email protected]" teacher.email_was # => "[email protected]" teacher.email # => "[email protected]" teacher.save # update example using "update_attribute" teacher = Teacher.last teacher.update_attribute(:email, '[email protected]') # update example using 'update_attributes' teacher.update_attributes(email: '[email protected]', first_name: 'soemthing_else') # add additional fields to teachers teable: # 1) generate a migration # 2) run the migration (test both up and down) # update the whole table for a specific field Teacher.update_all(age: 40) # update the whole table for multiple fields Teacher.update_all(age: 40, gender: 'male') # Destroy examples t = Teacher.first t.destroy # destroys a single object # destroys all the records of the table Teacher.destroy_all # validations t = Teacher.new t.save # => false t.errors # => complete error object t.errors.full_messages # => array of complete error messages # only validate but do not try to save t.valid? # => if returns false, i.e. there are errros... and if returns true, i.e. all validations are correct and there are no errors. t.photos
t = Teacher.first
t.photos << Photo.new(filename: "my_photo.jpeg", file_type: "JPEG") Photo.count p = Photo.first p.teacher p.photogrphable p.photographable.is_a?(Teacher) s.photos << Photo.new(filename: "some.png", file_type: "PNG") p.photographable
p = Photo.last p.photographable