CS代写 Associations, Validation,

Associations, Validation,
Computer Science and Engineering  College of Engineering  The Ohio State University

Associations (1:N Relationship)

Copyright By PowCoder代写 加微信 powcoder

Computer Science and Engineering  The Ohio State University
name (string)
Wicked Wicky
The Happy Crew
buckid (integer)
team_id (foreign key)

Invariants
A student belongs to exactly 1 team Weaker: A student belongs to at most 1 team
Students can only be added with team_id set to something valid
Same representation for either invariant A column (of foreign keys) in students table
Maintaining stronger invariant
Deleting a team deletes member students!
Maintaining weaker invariant
Students can be added with null team_id
Deleting a team null-ifies members’ team_id
Computer Science and Engineering  The Ohio State University

Rails Migration and Models
Computer Science and Engineering  The Ohio State University
class AddTeamForeignKeys < ActiveRecord::Migration def change add_reference :students, :team, index: true # for quick load class Student < ApplicationRecord belongs_to :team # note singular form # have Student#team method class Team < ApplicationRecord has_many :students # note plural form # have Team#students method Association Method Belongs_to creates method for accessing owner @student = Student.find 1 #=> 22352022 @student.team #=> ‘Wicked Wicky’ @student.team.name = ‘Evil Wicky’
Has_many creates method for accessing members
@team = Team.find 1
@team.students #=> array of students @team.students.first @team.students.size @team.students.destroy_all @team.students.any? { |s| … }
Computer Science and Engineering  The Ohio State University

Asymmetry in Writes to Assoc.
Computer Science and Engineering  The Ohio State University
Add a student to a team’s association:
student automatically saved (assuming team
is stored in database)
t = Team.find 1
t.students #=> []
t.students << Student.new # gets an id t.students #=> [#]
Set a student’s association to a team:
student is not automatically saved
s = Student.find 1
s.team = my_team
s.reload #=> s’s team is unchanged

Modifiers for belongs_to
Computer Science and Engineering  The Ohio State University
class Student < ApplicationRecord belongs_to :greek_house, optional: true # allows foreign key to be null belongs_to :project_group, class_name: 'Team' # default is Project_Group belongs_to :major, foreign_key: 'OSU_code' # default is major_id belongs_to :team, touch: :membership_updated Modifiers for has_many Computer Science and Engineering  The Ohio State University class Team < ApplicationRecord has_many :students, # max number of members dependent: :destroy, # what happens to dependents # when parent is destroyed? class_name: 'OSUStudent' # default is Student More Relationships 1:1 (one-to-one) Computer Science and Engineering  The Ohio State University Use belongs_to with has_one has_one is just has_many with limit of 1 A third, intermediary table is used with 2 columns (for foreign keys from two tables) Same asymmetry in writing exists N:M (many-to-many) In rails, use has_many :through association Validations Computer Science and Engineering  The Ohio State University  Invariants on the data in a table  To maintain invariant:  These "validations" are in the model student = Student.new lname: 'Vee' student.valid? #=> false (no buckid) student.save #=> false
Every student has a (non-null) buckid Buckids are unique
Team names are less than 30 characters Usernames match a regular expression
Must be true initially
Must be satisfied by each insertion
A model instance can be checked Invalid objects can not be saved

Rails Implementation
Computer Science and Engineering  The Ohio State University
Model object has an errors attribute This attribute is a hash (of problems)
Failing a validity check adds an item to
the errors hash
there’s a general key, :base s.errors[:buckid] = “is not a number”
Empty hash corresponds to valid object
Each attribute is a key in the errors hash, plus
The valid? method does the following: Empties errors hash
Runs validations
Returns errors.empty?

class Post < ApplicationRecord validates :name, presence: true validates :title, presence: true, Computer Science and Engineering  The Ohio State University length: { minimum: 5, maximum: 50 } Validates Method in Model Computer Science and Engineering  The Ohio State University validates :column, condition  Uniqueness uniqueness: true uniqueness: {message: 'Username already taken'}  Non-nullness (not the same as being true!) presence: {message: 'Title needed'}  Truth of a boolean field acceptance: {message: 'Accept the terms'}  Matching a regular expression format: {with: /[A-Z].*/, message: ...} format: /[A-Za-z0-9]+/  Being a number numericality: {only_integer: true}  Having a length length: {minimum: 5} Alternative: Declarative Style Computer Science and Engineering  The Ohio State University Special methods for each flavor of validation validates_uniqueness_of :username validates_presence_of :password validates_acceptance_of :terms validates_format_of :name, with: /[A-Z].*/ validates_numericality_of :buckid, only_integer: true Computer Science and Engineering  The Ohio State University Associations 1:N (or 1:1) relationships via foreign keys Rails methods belongs_to, has_many Create association attributes, which can be read and written Asymmetry in writing owner vs member Validations Invariants checked before saving Errors hash contains list of problems Declarative style for common case checks Custom validity checkers possible too To Ponder (recall..) Computer Science and Engineering  The Ohio State University Request: should be safe (no side effects) Update (or create): should be idempotent Delete: should be idempotent HTTP does not enforce these semantics Create (or update): changes server state Beware re-sending! Recall: Rails Architecture Computer Science and Engineering  The Ohio State University Configuration Computer Science and Engineering  The Ohio State University Need to map an HTTP request (verb, URL, parameters) to an application action (a method in a Ruby class) These mappings are called routes Defined in config/routes.rb Framework invokes the method, passing in parameters from HTTP request as arguments Results in an HTTP response, typically with an HTML payload, sent back to client's browser Ruby code, but highly stylized (another DSL) Checked top to bottom for first match Basic Route Computer Science and Engineering  The Ohio State University  Pattern string + application code  Example route get 'status/go/:system/memory/:seg', to: 'reporter#show'  Matches any HTTP request like GET /status/go/lander/memory/0?page=3 In config/routes.rb Pattern string usually contains segments params = { system: 'lander', Instantiates ReporterController Invokes show method on that new instance Provides an object called params (like a hash) page: '3' } Default Values  Special segments  Example route get ':controller/go/:action/:system'  Matches any HTTP request like GET /reporter/go/show/lander?page=3 Computer Science and Engineering  The Ohio State University :controller - the controller class to use :action - the method to invoke in that controller params = { system: 'lander', Instantiates ReporterController Invokes show method on that new instance Provides an object called params page: '3', # also :controller & :action } Customizing Routes Recognize different HTTP verb(s) Optional segments with ( ) get ':controller(/:action(/:id))' Default values get 'photos/:id', to: 'photos#show', defaults: { format: 'jpg' } get, put, post, delete Alternative: match via: [:get, :post] Computer Science and Engineering  The Ohio State University REpresentational State Transfer An architectural style for web applications GET, POST, PUT, DELETE The protocol is stateless Resource: bundle of (server-side) state Each resource is identified by a URL Maps database operations to HTTP requests Small set of database operations (CRUD) Create, Read, Update, Delete Small set of HTTP verbs, with fixed semantics (e.g., idempotence) Computer Science and Engineering  The Ohio State University A resource could be an individual member Example: a single student A resource could be a collection of items Corresponds to a row in a table Example: a set of students Corresponds to a table In REST, resources have URLs Each member element has its own URL http://quickrosters.com/students/42 http://quickrosters.com/students A collection has its own URL Computer Science and Engineering  The Ohio State University Read Collection: GET Computer Science and Engineering  The Ohio State University GET /students HTTP/1.1 Host: quickrosters.com Read Collection: GET Computer Science and Engineering  The Ohio State University GET /students HTTP/1.1 Host: quickrosters.com Read Collection: GET Computer Science and Engineering  The Ohio State University HTML Source (GET Collection)

Students

Fname Lname Buckid Primo Carnera 334432 Show Edit Destroy


Computer Science and Engineering  The Ohio State University

Read Member: GET
Computer Science and Engineering  The Ohio State University
GET /students/3

Minimal Set of Routes (R)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member

Minimal Set of Routes (CR)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
How to map “create member” action? Member doesn’t exist : target is collection
Creation is not idempotent : verb is…

Minimal Set of Routes (CR)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
Create a new member
How to map “create member” action? Member doesn’t exist : target is collection
Creation is not idempotent : verb is…

Minimal Set of Routes (CRU)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
Create a new member
How to map “update member” action? Target is a member
Update overwrites, so it is idempotent…

Minimal Set of Routes (CRU)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
Update member
Create a new member
How to map “update member” action? Target is a member
Update overwrites, so it is idempotent…

Minimal Set of Routes (CRUD)
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
Update member
Create a new member
Delete this member
Delete action destroys a member

Minimal Set of Routes
Computer Science and Engineering  The Ohio State University
Collection
/students/42
List all members
Show info about a member
Update member
Create a new member
Delete this member
Implications
You can’t delete a collection
No idempotent operations on collection

Typical Workflow: Delete
Computer Science and Engineering  The Ohio State University
How does one destroy a member? Need to issue an HTTP request:
DELETE /students/4
Alternative:
GET the collection to see the list Click a button next to one item in the list to issue a DELETE for that member
GET the member to see the details
Click a button to issue a DELETE for that member

GET List, DELETE Member
Computer Science and Engineering  The Ohio State University
GET /students
DELETE /students/4

Typical Workflow: Create
Computer Science and Engineering  The Ohio State University
How does one issue a POST on
collection?
That first GET is a new route
GET a (blank) form
Fill in fields of form
Click a button to submit, resulting in the POST
GET on the collection
But instead of a list of members, the
result is a form to be filled in and

GET Blank Form, POST the Form
Computer Science and Engineering  The Ohio State University
GET “a blank form”
POST /students
lname: …etc

Standard Set of Routes
Computer Science and Engineering  The Ohio State University
Collection
/students/42
1. List all members
2. Form for entering a new member’s data
1. Show info about a member
Update member
Create a new member
Delete this member

HTML Source

Students

Fname Lname Buckid

Computer Science and Engineering  The Ohio State University

Primo Carnera 334432 Show Edit Destroy

Typical Workflow: Update
Computer Science and Engineering  The Ohio State University
How does one issue a PUT on a member?
That first GET is a new route
GET a (populated) form
Edit the fields of the form
Click a button to send, resulting in the PUT
GET on a member
But instead of a display of information about that member, the result is a populated form to modify and submit

GET Filled Form, PUT the Form
Computer Science and Engineering  The Ohio State University
GET “a populated form”
PUT /students/4
lname: …etc

Standard Set of Routes
Computer Science and Engineering  The Ohio State University
Collection
/students/42
1. List all members
2. Form for entering a new member’s data
1. Show info about a member
2. Form for editing an existing member’s data
Update member
Create a new member
Delete this member

HTML Source

Students

Fname Lname Buckid

Computer Science and Engineering  The Ohio State University

Primo Carnera 334432 Show Edit Destroy

Rails Resource-Based Routes
Computer Science and Engineering  The Ohio State University
For a resource like :students, the action pack
1 controller (StudentsController)
7 routes (each with a method in controller)
4 Views (list of students, show 1 student, new, edit)
Response (View)
Collection
Collection
/students/new
Collection
blank form
/students/3
/students/3/edit
filled form
/students/3
/students/3

Defining Resource-Based Routes
Computer Science and Engineering  The Ohio State University
In RosterTool app’s config/routes.rb Rails.application.routes.draw do
resources :students
resources :faculty

Customizing Routes
Computer Science and Engineering  The Ohio State University
 To change which 7 routes are created resources :students, except:
[:update, :destroy] resources :grades, only: [:index, :show]
 To specify a particular controller resources :students, controller: ‘ugrads’
 To rename certain actions resources :students, path_names:
{ create: ‘enroll’ }
 To add more routes to standard set
 Add GET /students/:id/avatar (i.e. on member)  Add GET /students/search (i.e. on collection) resources :students do
get ‘avatar’, on: :member
get ‘search’, on: :collection end

Segment Keys
URL request has arguments for controller Example: products/42
Segment key gets value when route matches
Controller gets a hash (called params)
of segment keys and their values
Common case: Look up an item by id
def set_product
@product = Product.find(params[:id])
Computer Science and Engineering  The Ohio State University
Pattern string: ‘products/:id’
Example: params[:id] is ’42’

Recognition vs Generation
 Dual problems
 Routes used for both!
 For generation, route must be named
get ‘status/:seg’, to: ‘reporter#show’,
 Results in two helpers (_path, _url) info_path(4)#=> “/status/4”
info_url(4) #=> “http://faces.com/status/4”
 Used with link_to to generate hyperlinks link_to ‘S’, info_path(4), class: ‘btn’ #=> “S
Recognize a URL (request for an action)
Generate a URL (a hyperlink or redirect)
Computer Science and Engineering  The Ohio State University

Helper Methods for Resources
Computer Science and Engineering  The Ohio State University
 Resource-based routes have names
photos_path
photos_url
new_photo_path
photo_path(:id)
edit_photo_path(:id) #=> /photos/4/edit
#=> /photos
#=> http://faces.com/photos
#=> /photos/new
#=> /photos/4
Collection
Collection
/photos/new
Collection
edit_photo
/photos/3/edit

Debugging Routes and Helpers
Computer Science and Engineering  The Ohio State University
 To see the full list of routes
$ rails routes
Prefix Verb URI Contr#Action
info GET /status/:seg reporter#show
photos GET /photos photos#index
POST /photos photos#create photo GET /photo/:id photos#show edit_photo GET /photos/:id/edit … …etc…
 To see/use helpers in the console $ rails console
> app.edit_photo_path(42)
=> “/photos/42/edit”
> helper.link_to “Click here”,
app.edit_photo_path(42)
=> “Click here

Root Route
With no matching route, GET for http: //example.com gets index.html from
application’s public directory
To customize landing page, 2 choices:
root to: “welcome#index”
Create public/in

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com