ActiveRecord Mechanics

ActiveRecord DB Mechanics

NB If you don't know the schema of your app, you don't know your app!

Rails environments

  • Rails server “modes” (technically they are environments)
  • rails server -e production (for Rails)
  • Note that on Heroku deployment the environment is automatically set to production

What does the choice of environment affect?

  • WHich of the actual databases are used (see config/database.yml)
  • development - working on your own computer, developing
  • test - running tests
  • production - working on Heroku for example
  • Gemfile - which gems are installed
  • Various caching settings
  • And more

Going Deeper on ActiveRecord

  • Object Relational Mapper
  • Model class
  • ORM means we have to keep the database and the Objects “in sync”
  • 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

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
    • <%= link_to_topic :ar_db_types %>
    • <%= link_to_topic :ar_migrations %>

Associations

  • While this is basic Rails it is also some of the more “magical” parts of Rails which can sometimes be confusing
  • You know that to create a one to many relationship you need a foreign key in the “many” table
  • That is a basic relational database concept
  • You access this in an OO way by also telling ActiveRecord
  • It seems redundant but they are separate
  • The Rails Guide To Associations is a good place to start

Updating the Model source files


* `has_many :comments`
* `belongs_to :answer`

class Answer < ApplicationRecord
  belongs_to :question
  has_many :comments
end

# allows the following
q = Question.create(question: "What is the meaning of life?")
a = q.answers.create(body: "42")
a.comments.create(body: "I agree")

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