0% found this document useful (0 votes)
10 views16 pages

Active Record

Uploaded by

Matias Manara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Active Record

Uploaded by

Matias Manara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

https://github.

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

class Post < ActiveRecord::Base

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

Model Name vs. Table Name

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.

The Product class is automatically mapped to the table named “products”

This would also de ne the following accessors: Product#name and Product#name=(new_name)

https://edgeguides.rubyonrails.org/active_record_basics.html
fi
ActiveRecord Basics

Associations between objects de ned by simple class methods.

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')

users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)

user = User.create(name: "David", occupation: "Code Artist")


Creators
user = User.new
user.name = "David"
user.occupation = "Code Artist"
user.save

user = User.find_by(name: 'David')


user.update(name: 'Dave')
Associations
Belongs_to and has_one

╔═══════╤══════╤═══════════╗ ╔═════════╤══════╗
║ posts │ │ ║ ║ authors │ ║
╠═══════╪══════╪═══════════╣ ╠═════════╪══════╣
║ id │ name │ author_id ║ ║ id │ name ║
╚═══════╧══════╧═══════════╝ ╚═════════╧══════╝

class Post < ActiveRecord::Base class Author < ActiveRecord::Base


belongs_to :author has_one :author
. . . . . .
end end

post = Post.create(name: 'hi!')


post.author = Author.first(name: 'Sharon')
post.author
Associations
has_many

╔═══════╤══════╤═══════════╗ ╔══════════╤═════════╤═════════╗
║ posts │ │ ║ ║ comments │ │ ║
╠═══════╪══════╪═══════════╣ ╠══════════╪═════════╪═════════╣
║ id │ name │ author_id ║ ║ id │ content │ post_id ║
╚═══════╧══════╧═══════════╝ ╚══════════╧═════════╧═════════╝

post = Post.create(name: 'hi!')


post.comments
class Post < ActiveRecord::Base
. . . comment = Comment.create(text: 'hi')
has_many :comments post.comments << comment
end
post.delete(comment)

post.comments.delete_all
Associations
has_many :through

╔════════════╤══════╗ ╔══════════╤══════╗
║ physicians │ ║ ╔════════════════════════╤════════════╗ ║ patients │ ║
╠════════════╪══════╣ ║ appointments │ ║ ╠══════════╪══════╣
║ id │ name ║ ╠═════════╤══════════════╪════════════╣ ║ id │ name ║
╚════════════╧══════╝ ║ id │ physician_id │ patient_id ║ ╚══════════╧══════╝
╚═════════╧══════════════╧════════════╝

class Physician < ActiveRecord::Base class Patient < ActiveRecord::Base


has_many :appointments has_many :appointments
has_many :patients, :through => :appointments has_many :physicians, :through => :appointments
end end

class Appointment < ActiveRecord::Base


belongs_to :physicians
belongs_to :patient
end
Migrations
Allow you to evolve your database schema over time. Rather than write schema
modi cations in pure SQL. Migrations allow you to use Ruby DSL to describe changes to
your tables

DSL to create a Table

class CreateUsers < ActiveRecord::Migration[7.0]


def change
create_table :users do |t|
t.string :name
end
end
end

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:create_migration # Create a migration (parameters: NAME, VERSION)

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:migrate # Migrate the database (options: VERSION=x, VERBOSE=false)

rake db:migrate:status # Display status of migrations

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:schema:load # Load a schema.rb le into the database

rake db:seed # Load the seed data from db/seeds.rb

rake db:setup # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db rst)

rake db:structure:dump # Dump the database structure to db/structure.sql

rake db:version # Retrieves the current schema version number


fi
fi
fi
fi
fi
fi
fi
Resume
References
https://api.rubyonrails.org/classes/ActiveRecord/Base.html

https://github.com/rails/rails/tree/main/activerecord

https://api.rubyonrails.org/classes/ActiveRecord/Base.html

You might also like