DEV Community

James Shipman
James Shipman

Posted on • Updated on

ActiveRecord & Rake cheatsheet

There is a lot to learn when first learning ActiveRecord and Rake. So much so that I created a cheatsheet for myself. This is a quick reference guide for the basic folder structure ActiveRecord (just AR for now) and Rake look for as well as what each file needs to get everything up and running.

Folder Structure

root.
./ < Gemfile >
./ < Rakefile >
./app
./app/models/ < model_file.rb >
./bin < run.rb >
./config < environment.rb >
./db < seeds.rb >, < schema.rb >
./db/migrate/ < 001_migration_file.rb >

Files

For each file there are some basics that each file needs and ActiveRecord. Here is each file as noted above.

  1. Gemfile - this file lists all gems being used in your app. Note in the line for activerecord it calls to a version number, this is optional.

    source "https://rubygems.org"
    
    gem "activerecord", '~> 5.2'
    gem "sinatra-activerecord"
    gem "sqlite3", '~> 1.3.6'
    gem "pry"
    gem "require_all"
    
  2. Rakefile - this file establishes connections within the folder structure and creates a live environment through rake console that allows for testing.

    require_relative 'config/environment'
    require 'sinatra/activerecord/rake'
    
    desc 'starts a console'
    task :console do
      ActiveRecord::Base.logger = Logger.new(STDOUT)
      Pry.start
    end
    
  3. model_file - these are highly specific but the minimum. This file acts as the model that matches a table in the app's database. It is a good idea to keep the name here matched to migration file and table that this model file provides custom functionality to.

    class ModelName < ActiveRecord::Base
    end
    
  4. run.rb

    require_relative '../config/environment'
    
  5. environment.rb

    require 'bundler'
    Bundler.require
    
    require 'active_record'
    
    ActiveRecord::Base.establish_connection(
      adapter: 'sqlite3', 
      database: 'db/development.db'
      )
    
    require_all 'app/models'
    
  6. seeds.rb - this file will contain test data that can be loaded into the app's database. Prior to creating the seed data it is a great idea to have a line per model that deletes everything out of the data table for that model. This way the seed data can be reloaded as needed and old data will be removed.

    Model.delete_all
    
  7. schema.rb - This file is created by ActiveRecord, do not edit it manually but it is good to reference back to it as it will contain the lastest version of the schema for all tables within your database.

  8. 001_migration_file.rb

    class CreateProteinTable < ActiveRecord::Migration[5.2]
      def change
        create_table :proteins do |t|
          t.string :name
        end
      end
    end
    

Top comments (0)