Active Record
Active Record
com/rails/rails/tree/main/activerecord
https://github.com/sinatra-activerecord/sinatra-activerecord
ORM
Object Relational Mapping
get '/' do
@user = current_user
erb :landing
end
Models
Model
end
Dataset
posts
Instance
post = Post.find(123)
Convention Over
Con guration
Convention over con guration is a software design paradigm used by software frameworks
that attempt to decrease the number of decisions that a developer using the framework is
required to make without necessarily losing exibility
Singular Plural
users
class User < ActiveRecord::Base
Column | Type
end
—————+-———-
id | integer
name | text
fi
fi
fl
CoC
ActiveRecord Basics
Automated mapping between classes and tables, attributes and columns.
https://edgeguides.rubyonrails.org/active_record_basics.html
fi
ActiveRecord Basics
fi
Models
A model class forwards many methods to the underlying dataset
user.name = 'Dave'
user.name
# => 'Dave'
Accessors
user.attributes #> { id: ‘1’, name: ‘Dave' }
users = User.all
user = User.first
Querying
david = User.find_by(name: 'David')
╔═══════╤══════╤═══════════╗ ╔═════════╤══════╗
║ posts │ │ ║ ║ authors │ ║
╠═══════╪══════╪═══════════╣ ╠═════════╪══════╣
║ id │ name │ author_id ║ ║ id │ name ║
╚═══════╧══════╧═══════════╝ ╚═════════╧══════╝
╔═══════╤══════╤═══════════╗ ╔══════════╤═════════╤═════════╗
║ posts │ │ ║ ║ comments │ │ ║
╠═══════╪══════╪═══════════╣ ╠══════════╪═════════╪═════════╣
║ id │ name │ author_id ║ ║ id │ content │ post_id ║
╚═══════╧══════╧═══════════╝ ╚══════════╧═════════╧═════════╝
post.comments.delete_all
Associations
has_many :through
╔════════════╤══════╗ ╔══════════╤══════╗
║ physicians │ ║ ╔════════════════════════╤════════════╗ ║ patients │ ║
╠════════════╪══════╣ ║ appointments │ ║ ╠══════════╪══════╣
║ id │ name ║ ╠═════════╤══════════════╪════════════╣ ║ id │ name ║
╚════════════╧══════╝ ║ id │ physician_id │ patient_id ║ ╚══════════╧══════╝
╚═════════╧══════════════╧════════════╝
https://guides.rubyonrails.org/active_record_migrations.html
fi
Migrations
$ bundle exec rake -T
rake db:create # Create the database from DATABASE_URL or con g/database.yml for the current Rails.env (use db:create:all to create all dbs in the con g)
rake db:drop # Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)
rake db: xtures:load # Load xtures into the current environment's database
rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:dump # Create a db/schema.rb le that can be portably used against any DB supported by AR
rake db:setup # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db rst)
https://github.com/rails/rails/tree/main/activerecord
https://api.rubyonrails.org/classes/ActiveRecord/Base.html