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.
-
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"
-
Rakefile
- this file establishes connections within the folder structure and creates a live environment throughrake 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
-
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
-
run.rb
require_relative '../config/environment'
-
environment.rb
require 'bundler' Bundler.require require 'active_record' ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: 'db/development.db' ) require_all 'app/models'
-
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
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.-
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)