ActiveRecord Mechanics

ActiveRecord DB Mechanics

NB If you don't know the schema of your app, you don't know your app!
  • 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)

ActiveRecord model classes and instances

  • 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

Different database ‘servers’

  • SQLite - local database, no need for a server
  • MySQL - Standard industrial strength database, free
  • PostgreSQL - Becoming very popular with Rails community

Tools and Notes