Computer Science and Engineering College of Engineering The Ohio State University
Recall: Rails Architecture
Computer Science and Engineering The Ohio State University
Copyright By PowCoder代写 加微信 powcoder
Recall: Rails Architecture
Computer Science and Engineering The Ohio State University
Mapping Tables to Objects
Computer Science and Engineering The Ohio State University
General strategy for OO languages
Application works with database using
ordinary language syntax
Table in database — a class
Table columns — attributes of the class Table rows — instances of class (objects)
Class methods for finding row(s) in table Example: Java POJOs, Rails models
Directory Structure of Rails
Computer Science and Engineering The Ohio State University
……../controllers
……../helpers
……../models
……../views
…………../layouts
…./components
…./config
…./public
…./script
…./vendor
….README
….Rakefile
A Bit of Configuration
Which database to use?
Different environments: development, test, production
See config/database.yml default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") {5} %> timeout: 5000
development:
<<: *default
database: db/development.sqlite3
SQLite is the easiest (no setup!)
MySQL has better performance
PostgreSQL favored for Heroku deployment
Default (for rake command) is development
Computer Science and Engineering The Ohio State University
Database Tables
A database is a collection of tables Naming convention: Table names plural
Each table has a list of columns
Each column has a name and a type
A table has a list of rows
Computer Science and Engineering The Ohio State University
fname (string)
lname (string)
buckid (integer)
Database Column Types
Computer Science and Engineering The Ohio State University
Postgresql
tinyint(1)
varchar(255)
character varying
varchar(255)
Table Constraints
Computer Science and Engineering The Ohio State University
Invariants on table entries beyond type
information
Often useful to have a unique
identifier for each row (a "primary
"lname is not null"
"buckid is unique"
Easy: Include an extra (integer) column Database responsible for assigning this value every time a row is added
No way to change this value after creation
Primary Key With Autoincrement
Computer Science and Engineering The Ohio State University
fname (string)
lname (string)
buckid (integer)
Linking Tables
Computer Science and Engineering The Ohio State University
Different tables can be related to each
Keys are used to encode this relationship Include a column in table X containing keys from table Y ("foreign keys")
For examples:
Students table includes a column identifying a student's major
Vehicles table includes a column identifying a (student) owner
Association is an invariant between tables
"Each student has exactly 1 major"
"Each student can own 1 (or more) vehicles"
Association: Students & Vehicles
Computer Science and Engineering The Ohio State University
fname (string)
lname (string)
buckid (integer)
major (foreign key)
owner (foreign key)
license (string)
Associations
Computer Science and Engineering The Ohio State University
vehicles students programs
owner (for. key)
major (for. key)
Computer Science and Engineering The Ohio State University
Definition of table structure
Usually database manager-specific
See db/schema.rb for Ruby-based schema
description
Table name
Column names and types
Constraints
Allows independence from particular DB manager
Schema is versioned by timestamp (really by "migration"...)
Example schema.rb
Computer Science and Engineering The Ohio State University
ActiveRecord::Schema.define(version: 20180319144259) do
create_table "students", force: :cascade
t.string "name"
t.integer "buckid"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
Migrations
Computer Science and Engineering The Ohio State University
Q. Who writes schema.rb?
A migration is Ruby code (a class) that
represents a change in schema
A. It is generated!
Golden rule: Never edit schema.rb directly Instead, write a migration
Create new tables (including column names and column types)
Modify existing tables (adding/removing columns, or changing associations) Delete ("drop") existing tables
Migration Classes
See db/migrate
Computer Science and Engineering The Ohio State University
Consequence: Migrations are run in a
consistent order
Filename consists of Timestamp (UTC) of creation
Class name (descriptive of delta) Example: class CreatePosts in 20180319145307_create_posts.rb
Deltas do not commute, so order is important
Class extends ActiveRecord::Migration Contains method change
This method invoked by rails db:migrate
Example Migration Class
Computer Science and Engineering The Ohio State University
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
Result of raking this Migration
Computer Science and Engineering The Ohio State University
:name (string)
:title (string)
:content (text)
:created_at (datetime)
:updated_at (datetime)
Column Type Mappings
Computer Science and Engineering The Ohio State University
Postgresql
tinyint(1)
BigDecimal
varchar(255)
character varying
varchar(255)
:timestamp
Schema Deltas In Migrations
Computer Science and Engineering The Ohio State University
In addition to creating tables, the change method can also change existing tables
Example: xxx_add_author_to_posts.rb class AddAuthorToPosts <
ActiveRecord::Migration
def change
add_column :posts, :author, :string
Modify columns of an existing table
add_column, remove_column, rename_column,
change_column
Modify and delete tables
change_table, drop_table
Migrations as History
Computer Science and Engineering The Ohio State University
Change defined by migration can be undone
Can move forward/backward in history
Migrations give a linear history of deltas
Schema is the result of applying them (in order)
Create database only (no schema) defined in
config/database.yml
$ rails db:create
Update schema.rb (compare its version number to list
of migrations) and apply to database
$ rails db:migrate
Rollback schema.rb to earlier point in history
$ rails db:rollback
Load schema defined in db/schema.rb
$ rails db:schema:load
Schemas, Migrations, Models
Computer Science and Engineering The Ohio State University
migrations
database.yml
db:migrate
db:schema:load
db:schema:dump
Migrations vs Schema
Computer Science and Engineering The Ohio State University
Golden rule: Never edit schema.rb
It is regenerated every time you do a migration
Commit schema.rb to version control Deployment in fresh environment means loading schema, not reliving the full migration history
Every change in schema means writing a
Commit migrations to version control
Once a migration has been shared, to undo it
you should create a new migration (preserve the linear history)
Computer Science and Engineering The Ohio State University
Programmatic way for application to
interact with database
Collection of Ruby classes Extend ApplicationRecord Found in app/models
Each class corresponds to a table
Note: Models are singular (tables are plural)
class Post < ApplicationRecord
# attr_accessible :name,:title,:content
Includes attributes corresponding to columns
implicitly
Class Methods for Models
Computer Science and Engineering The Ohio State University
Create a new instance with new p1 = Post.new
p2 = Post.new author: "Xi", title: "Hola"
Create instance and add it to database p3 = Post.create author: "Zippy"
Retrieve particular row(s) from table
@post = Post.find 4 # search by id
@post = Post.find_by author: "Xi" @student = Student.find_by buckid: 543333 @blog = Post.all
@post = Post.first
@post = Post.last
Warning: this only creates the model (object) it does not modify the database
Instance Methods for Models
Computer Science and Engineering The Ohio State University
To save a model (object) as a row in the
p = Post.new author: 'Xi'
p.save # commits change to database
Read/write attributes like an ordinary Ruby
@post = Post.find_by author: 'Xi'
t = @post.title #=> nil
@post.title = ‘A Successful Project’ @post.save # don’t forget to save!
To delete a row from the table
@post.destroy # no save needed
Databases: Tables, columns, rows Structure defined in a schema
Rails uses Ruby code to generate schema
Computer Science and Engineering The Ohio State University
Migrations
Ruby code describing change to schema
Syntax look declarative
Ruby classes that mirror database tables
Class names from table (singular vs plural) Attributes from columns
Code generation
Database schema generated by schema.rb
Schema.rb generated by rails on migrations Migrations and models can be generated by rails
Schemas, Migrations, Models
Computer Science and Engineering The Ohio State University
migrations
database.yml
db:migrate
db:schema:load
Recall: Migrations
Computer Science and Engineering The Ohio State University
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
Recall: Models
Computer Science and Engineering The Ohio State University
class Post < ApplicationRecord
# attr_accessible :name,:title,:content
Generating Code: rails generate
Computer Science and Engineering The Ohio State University
Notice: Two blobs of Ruby code need to be in sync
Single point of control: Generate both simultaneously $ rails generate model Student
fname:string lname:string buckid:integer
Use model name (singular) and attributes
Note: this does not generate the schema.rb (use rails)
Migrations for table edits can also be generated
$ rails generate migration AddNickNameToStudent nick:
Migration (creates table and columns)
db/migrate/xxx_create_students.rb
Model (with matching name)
app/models/student.rb
Name is meaningful! (starts with add or remove) Creates a migration that changes students table
Result of generate model
Computer Science and Engineering The Ohio State University
class CreateStudents < ActiveRecord::Migration def change
create_table :students do |t|
t.string :fname
t.string :lname
t.integer :buckid
t.timestamps
class Student < ApplicationRecord
Working With Models
Computer Science and Engineering The Ohio State University
> s = Student.new
> s2 = Student.new fname: “Jo”
> s3 = Student.new fname: “Xi”,
buckid: 23 > Student.all #=> ?
Working With Models
Computer Science and Engineering The Ohio State University
> s = Student.new
> s2 = Student.new fname: “Jo”
> s3 = Student.new fname: “Xi”,
buckid: 23
> Student.all #=> [] still
> Student.all #=> [
Computer Science and Engineering The Ohio State University
Quickly populate using config/seeds.rb
Use of Faker gem
$ rails db:migrate:reset
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com