跳到主要內容

Ruby on Rails 安裝

Ruby on Rails 是另一種網站建置的架構,主要的優點在於容易維護,底下是在 Windows 7 中安裝的過程:

1. 從[1]中下載 Ruby 的 windows installer 安裝

2. 開啟「 Start Command Prompt with Ruby」,然後設定 command line 的編碼為 unicode

3. 安裝 sqlite3, $ gem install sqlite3

4.安裝 rails, $ gem install rails

5. 新增網站的目錄, $ mkdir C:/www/rails

6. $ cd C:\www\rails

7. $rails new demo

8. 啟動 rails, $ rails server

9. 連線測試: http://localhost:3000/

在 Windows 7 底下開啟「 Start Command Prompt with Ruby」時,預設是在 C:\Users\elvis\rails,而實際在檔案總管中是 C:\使用者\elvis 目錄。

Rails 提供 bundler 來檢查 gem 套件的相依性,只要在 demo 目錄中輸入 $ bundle install, or bundle 就會檢查並安裝相依的套件,如果你修改 Gemfile 時,必須要執行 $ bundle 。

Rails 是依照 Model/View/Control(MVC) 的架構來管控網站的內容,首先要先產生一個 Controller 的相關檔案,然後再編輯 Control/View 以及 router 的設定,以下是參考[2]的說明產生第一個 Hello World 的網頁。

1. 產生Controller 的相關檔案, $ rails generate controller welcome, or rails g controller welcome

2. 編輯demo/config/routes.rb 檔,加入下列一行設定
   get "welcome/say_hello" => "welcome#say"

3. 編輯 app/controllers/welcome_controller.rb,加入一個方法:
    class WelcomeController < ApplicationController
    end
    def say
    end
4.  新增app/views/welcome/say.html.erb 這個檔案,內容為:
     <h1>Hello, World!</h1>

5. 測試 http://localhost:3000/welcome/say_hello

Rails 預設的首頁是 public/index.html ,這個網頁也就是 http://localhost:3000 所看到的內容,系統會自動導向這個網頁,可以刪除 public/index.html 檔,然後修改 routes.rb 來導向其他檔案來當成網站的首頁,設定的方法如下:

1. 修改 config/routes.rb 檔,加入下列設定:
    root :to => "welcome#index"

2. 設定連結回首頁的設定:
  <p><%= link_to "Home", root_path %></p>
 

----------------------------------------------------------
[1] http://rubyonrails.org/download
[2] http://ihower.tw/rails3/firststep.html

留言