ruby on rails kickstart 103 & 104

Post on 26-Jan-2017

197 Views

Category:

Presentations & Public Speaking

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Ruby on Rails#103 Scaffold and modify scaffold

ScaffoldRuby on Rails magic

Getting started1. Ruby on Rails command

2. Generate an article scaffold

• MVC pattern

3. Synchornize database schema

• ORM

4. Modify scaffold

Ruby on Rails Commandrails generate scaffold scaffold_name field1_name:field1_type \ field2_name:field2_type ... fieldN_name:fieldN_type

• Replace scaffold_name with actual scaffold names

• Replace field1_name to fieldN_name with actual field names

Ruby on Rails command (Cont.)field1_type to fieldN_type needs to be a valid data type

source: https://ihower.tw/rails4/migrations.html#section

Generate an article scaffoldrails generate scaffold article title:string body:text

The command generates...

• a controller handles requests from clients and transfer data between models and views

• a model with one string field called title and one text field body called article

• a form for create and update articles and several views to list articles and to display single article

Controller? Model? View?What the hell are they?

MVC pattern

Models and views DO NOT directly exchange data

Remember this till the Apocalypse

Synchronize database schemarake db:migrate

• rake runs scripts called Rakefile. Rakefile holds a bundle of commands related to Ruby on Rails but not part of Ruby on Rails

• db:migrate: synchronize database schema, as known as database migration

• tmp:clear: clean temporary files

Why bothered?In PHP

$title = mysql_real_escape_string($_POST['title']);$body = mysql_real_escape_string($_POST['body']);$sql = "INSERT INTO `articles` (`title`, `body`)" . " VALUES ('{$title}', '{$body}')";mysql_query($sql);

SucksJust one SQL injection can

make your system upside down

ONE SQL INJECTION!

Don't botherIn Ruby on Rails# params[:article] = {# title: 'Article title',# body: 'Article body'# }

article = Article.new(params[:article])article.save

ORM saves the day

ORMObject Relational Mapping

ORM (Cont.)• Object Relational Mapping

• Object stands for objects in Ruby on Rails

• Relational stands for relational database system, such as MySQL, PostgreSQL, Microsoft SQL Server...etc.

• Mapping stands for the procedure transfer data structure into table row

Start web serverIf you forget how to do so,

feel free to take a look on #101

Open browserhttps://[your-cloud9-preview-url]/articles

If you see this, you got it

Just one command...fulfills fundamental needs

Modify scaffoldAdd / Remove a field

Nobody is perfect

Add a field1. Modify model

1. Create a database migration

2. Synchronize database schema

2. Modify the controller

3. Modify views

Create a database migrationrails generate migration \ add_author_to_articles author:string

• Replace author with field name you want to add

• Replace articles with plural form of model

• Replace string with valid data type from the table mentioned before

Synchronize database schemarake db:migrate

Modify the controller# Only allow a trusted parameter "white list" through.def article_params params.require(:article).permit(:title, :body, :author)end

• Append :author to the list of white list

Strong parameterOnly allow values of known keysto be assigned to the ORM object

Modify views1. index view2. show view3. _form partial

index view... <td><%= article.body %></td> <td><%= article.author %></td> <td><%= link_to 'Show', article %></td>...

show view...</p>

<p> <strong>Author:</strong> <%= @article.author %></p>

<%= link_to 'Edit', edit_article_path(@article) %> |...

_form partial... <%= f.input :body %> <%= f.input :author %> </div>...

FiveCount of files you edited for adding a field

Ruby on Rails magic

Remove a field from scaffold1. Create a database migration

2. Synchronize database schema

3. Modify the controller

4. Modify views

Database migrationAny changes related to database,

including adding or removing fields

Create a database migrationrails generate migration remove_body_from_articles

• Replace author with field name in the model

Synchronize database schemaThat's all I can say

Modify the controllerReverse procedure against adding fields

Modify viewsReverse procedure against adding fields

End of Ruby on Rails #103

Ruby on Rails#104 Dig into MVC

Review

Controller1. Receive requests

2. Fetch raw or processed data from models

3. Inject data into views

Controller (Cont.)class SomeController < ApplicationController ... def action_name ... end ...end

Controller (Cont.)1. One controller has many actions

2. Each action has its own purpose

3. Actions are isolated to each other

4. One action takes care of one request

Model1. Query rows from database

2. Process data

3. Write data into database

Model (Cont.)class Person

def full_name first_name + last_name end

end

Model (Cont.)1. Model DOES NOT hold fields, schema DOES

2. Model is a class

3. In ORM, fields would be mapped as properties in object, thus we can manipulate them via methods

Model (Cont.)• HumanBeing : Model

• Person : Object

• People : Iterable object (a.k.a. array) of objects

Model (Cont.)@all_people = HumanBeing.all

@adults = HumanBeing.where('age >= ?', 20)

@person = HumanBeing.find_by(identity: 'A123456789')

Views1. Build HTML documents

2. Respond to clients

Views (Cont.)Full name: <%= @person.full_name %>

Where does @ point to?

Views (Cont.)1. Symbol @ points to corresponding controller in views

2. DO NOT conduct complicated calculations or property access in views

3. Views should have only if and each statements

Homework1. Create a scaffold from scratch

2. Add a field to the scaffold

3. Remove a existing field from the scaffold

top related