ActiveRecord Mechanics

ActiveRecord DB Mechanics

  • Concepts
    • Object Relational Mapper
    • Model class
    • ORM means we have to keep the database and the Objects “in sync”
  • Rails/Sinatra server “modes” (technically they are environments)
    • rails server -e production (for Rails)
    • `set :environment, :development (for Sinatra)
    • Actually these modes are ActiveRecord modes!
    • Modes will affect what database to use, whether caching is enabled or not, and numerous other things
      • development - working on your own computer, developing
      • test - running tests
      • production - working on Heroku for example
  • ActiveRecord
    • Library from Ruby on Rails which is the connection between the rails application and the underlying database
    • For advanced designs, there are options other than ActiveRecord
    • ActiveRecord is also often used by itself, especially in Sinatra
  • Naming
    • Model.rb file is named singular, e.g. User
    • Corresponding db table is plural and lower case, e.g. users
  • Correspondences
    • Each instance of the class (e.g. User) corresponds to a single record in the database
    • When a query returns a bunch of records, you get a collection of instances of the class
    • (this is classic Active Record model)
  • Attributes
    • Rails will automagically create the methods to access each field (column) of the record in the database
  • Two copies!
    • Instance of the class, in memory
    • Corresponding record in database
    • One or the other or both may exist!
    • Need to save, need to query, etc.
  • Datatypes supported by ActiveRecord
  • CRUD: Reading and Writing Data
    • NB: memory vs. persisted copy of the object
    • Create: create record and persist it
    • New: create model object without persisting it
  • Queries and other ways to access the database
  • Updating
    • Retrieve the object (.where etc), modify the attribute, and save it
  • Deleting
    • Retrieve the object and .destroy (also class method .destroy_all)
  • Validations
  • Different database ‘servers’
    • Sqllite - local database, no need for a server
    • MySql - Standard industrial strength database, free
    • Postgress - Becoming very popular with Rails community
  • Tools and notes