ruby -e "puts Time.now.strftime('%Y-%m-%d %H:%M:%S')"。gem install rails --include-dependencies(需聯網)。development/test/production 三個資料庫。rails autoweb cd autoweb # 修改 config/database.yml 密碼 ruby script/generate scaffold Record Admin ruby script/server
瀏覽 https://localhost:3000/admin 即擁有完整 CRUD 介面。
ActiveRecord::Base,慣例類別名單數對應資料表複數(Record → records)。set_table_name 覆寫表名,establish_connection 直接在程式碼設定連線。:encoding => "gb2312" 或 utf8 以正確儲存中文。CREATE TABLE records ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(50) NOT NULL, content MEDIUMTEXT NOT NULL, date CHAR(10) NOT NULL, UNIQUE KEY (date) ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
class Record < ActiveRecord::Base
establish_connection(
:adapter => "mysql", :host => "localhost",
:username => "root", :password => "password",
:database => "diary", :encoding => "gb2312"
)
end
ApplicationController,每個 public 方法對應一個 URL 路徑。before_filter :configure_charsets 設定 Content-Type: text/html; charset=gb2312 解決中文顯示。write(新增/編輯今日日記)、create(儲存)、query(查詢表單)、result(顯示結果)。置於 app/views/diary/,混合 HTML 與 Ruby 程式碼(如 <%= start_form_tag :action => 'create' %>、<%= render :partial => 'form' %>)。每個 Controller 動作必須有對應 .rhtml 檔案。
Rails 自動依照目錄結構 (app/models, app/views, app/controllers) 載入元件,零配置實現 MVC,遠勝 Struts 複雜的 XML 設定。ActiveRecord 提供強大的資料映射與關聯描述,配合 Web Services、Action Mailer、Security 等內建模組,讓 Ruby 快速開發強大 Web 應用成為可能。