Ruby on Rails 網站程式設計基礎班
Lesson 6
Quiz 2 解答
Review

Create a page
localhost:3000/users
- 建立 routing
- 建立 controller
- 建立 view
建立 Routing
localhost:3000/users
# 在 config/routes.rb 裡面
Rails.application.routes.draw do
# 增加一個叫 users 的 resource
resources :users
end
建立 Controller
localhost:3000/users
# 在 app/contollers 資料夾下新增一個檔案: users_controller.rb
class UsersController < ApplicationController
def index
end
end
建立 View
localhost:3000/users
<!--在 app/views 資料夾下新增一個資料夾 users,在 users 資料夾裡新增一個檔案 index.html.erb-->
<h1>This is Users Index Page!!!</h1>
<h1>Hello World</h1>
Relational Database
Relational Database
- 關聯性資料庫
- 今天我們用網路服務基本上就是在和資料庫做互動
- 資料的基本操作是 CRUD (create, read, update, delete)
- 使用 SQL 語言做搜尋
問題是 SQL 有些時候很煩...
- 等於是要再去學一個新的語言
- 資料表之間的關聯越複雜,搜尋的 SQL 指令就越複雜,變得很噁心
select name from users where name = 'Eugene Chang'
所以 Active Record 就誕生了
- 把資料庫表單抽象成 Ruby 的物件
- 所以我可以用 Ruby 的語法去操作資料庫
# 把一個 user 的資料存進 instance variable
@user = User.find_by_name("Eugene")
# 之後就可用 Ruby 語法直接取值
@user.name
@user.id
Rails Model
- 一個 Model 會和資料庫裡的一個資料表(Table)相對應
- 放在 app/models/ 資料夾裡
- 命名原則是 資料表名稱去掉 's'
# 在 app/models 資料夾下新增一個檔案 user.rb
# 然後宣告 User class
class User < ActiveRecord::Base
end
# 記住 User class 是對應到 users 資料表
在使用 ActiveRecord 之前...
需要先為 users 在資料庫裡建立一個資料表
Migration File (資料庫遷移檔)
$rails g migration add_users_table
- 接下來就去 app/db/migrate 下尋找 migration 檔,輸入:
- 今天若我要對 database 做出改變,就產生一個 migration 檔
class AddUsersTable < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :description
t.integer :age
t.timestamps
end
end
end
Migration File (資料庫遷移檔)
$rake db:migrate
- 編輯好 migration 檔之後:
- Rails 就會自動幫你把在 migration 檔裡設定的資料表建立好出來
Rails Model 小結
- Model 檔案對應到資料庫裡的資料表
- Active Record 把資料表物件化,可以用 Ruby 語法操作資料庫
- Migration 檔是當你要改變資料庫裡的欄位使用的東西,也是資料庫的版本控制
展現一下 Rails 的魔力
- 做出一個簡單的訂便當系統
- 創造一個能夠新增、查詢、編輯、刪除(CRUD) 的 app
# 使用 scaffold 指令
$rails g scaffold order title:string content:text url:string
建立 CRUD 的 SOP
- 寫 migration 檔建立 table
- 執行 rake db:migrate
- 到 /config 底下編輯 routes.rb 建立相關路由
- 到 app/controllers/ 建立 controller (table 名稱 + _controller.rb),把 action 都 def 出來
- 到 app/views/ 底下建立和 controller action 名稱相符的 .html.erb 檔案
功課 3
ntu_ror_261_lesson6
By Eugene Chang
ntu_ror_261_lesson6
- 806