โปรแกรมที่ Classic ที่สุดโปรแกรมหนึ่งนั้นคือ Hello World! แต่เราจะ Hello Rails! แทน มาลุยกันเลย
ต่อเนื่องจากตอนที่แล้วหลังจากเตรียมตัว Install Software ที่จำเป็นเสร็จเรียบร้อยแล้ว
ในตอนนี้เราจะมาเขียนโปรแกรมที่ Classic ที่สุดโปรแกรมหนึ่งนั้นคือ Hello World!
แต่เราจะ Hello Rails! แทน มาลุยกันเลย
SummerDayOnRails Environment
- Ruby Version : 1.8.6
- Rails Version : 2.0.2
- Web Server : Mongrel
- Database : MySQL
Hello Rails!
- สร้าง Rails Application
- Dubble Click InstantRails.exe (อยู่ภายใน Folder InstantRails ที่ unzip ออกมา)
- Click ตรงสัญลักษณ์รูปตัว I
- Rails Application >>> Open Ruby Console Windows
- พิมพ์ คำสั่ง ลงไปใน console
- rails -d mysql SummerDayOnRails
- cd SummerDayOnRails
-
Start Web Server
-
เปิด Ruby Console Windows ใหม่ขึ้นอีกหนึ่งอัน
- Click ตรงสัญลักษณ์รูปตัว I
- Rails Application >>> Open Ruby Console Windows
-
สร้าง Controller ชื่อ Say
-
cd SummerDayOnRails
- ruby script/generate controller Say
Rails จะ Generate file ให้ Controller หนึ่งในนั้นคือ say_controller.rb
อยู่ใน rails_apps/SummerDayOnRails/app/controllers
- สร้าง Action Hello ใน Controller Say
- rails_apps/SummerDayOnRails/app/controllers/say_controller.rb
-
class SayController < ApplicationController
def hello
end
end
เครื่องผมมันบังคับให้สร้าง Database : SummerDayOnRails_development ด้วย
และเข้าไปใ่ส่ password ใน file config/config/database.yml ใส่ username
password ของ Database ในเครื่องของท่าน
- สร้าง View
-
<html>
<head>
<title>Hello, Rails!</title>
</head>
<body>
<h1>Hello Rails!</h1>
</body>
-
</html>
save file ไปใว้ที่ app/views/say/hello.rhtml
สัังเกตว่า
app/views/say/hello.rhtml : หมายถึง View Layer ใน MVC
app/views/say/hello.rhtml : ชื่อเดียวกับ Controller ที่เราเพิ่งสร้างไป
app/views/say/hello.rhtml : ชื่อเดียวกับ Action ใน Controller Say
-
8. หน้าตา Hello Rails!
เรียบร้อยเท่านี้เราก็ได้ Hello Rails บันทึกต่อไปจะเป็นการอธิบายขั้นตอนการทำงานของ Rails
Hello Rails path 2