Ruby on Rails/示例
本節是Rails有用示例的集合。
rails 命令現在以 "rails" 開頭,而不是 "script/"
script/generate model <Name>
生成空的模型和遷移檔案。
vi db/migrate/XXX_create_<Name>.rb
向表中新增列。
rake db:migrate
遷移資料級別 - 即 - 建立新的資料庫表。
vi app/models/<Name>.rb
定義驗證、大小等。
vi test/unit/<Name>_test.rb
定義對模型驗證進行練習的單元測試。
如果將有與該模型關聯的控制器(和檢視)
script/generate controller <Name> <action_one> <action_two> ...
建立控制器併為每個操作建立檢視。
ActiveRecord 的 find 方法在Rails API 手冊中進行了說明
pet = Pet.find(pet_id) 透過id(整數)查詢記錄。注意:返回一個物件。pet_id 應該是主鍵數字。
pets = Pet.find(:first, :conditions => ["owner_id = ?", owner_id]) - 返回第一個匹配的記錄。[注意:返回一個物件。]
pets = Pet.find(:all, :conditions => ["owner_id = ?", owner_id]) - 查詢所有具有給定欄位值的記錄。[注意:1. 返回一個物件陣列。使用 pets.empty? 檢查是否沒有找到記錄pets.empty?. 2.:conditions =>提供與 WHERE *一起使用的 SQL 片段]
pets = Pet.find(:all, :conditions => ["owner_id = ? AND name = ?", owner_id, name]) - 查詢所有匹配多個欄位值的記錄。[注意OR也適用。]
pets = Pet.find(:all, :conditions => ["name LIKE ?", "Fido%"]) - 查詢所有匹配模式的記錄。萬用字元是%用於零個或多個任何字元,並且_用於任何單個字元。要轉義萬用字元,請使用\%或\_. 來自MySQL 的 LIKE 參考將有所幫助。在MySQL Regex 網站 上,您將找到使用 REGEX 的示例。
pets = Pet.find(:all, :order => 'name') - 查詢所有內容並按名稱排序結果。
pets = Pet.find(:all, :limit => 10, :conditions => ["owner_id = ?", owner_id]) - 返回不超過:limit 指定的行數。
pets = Pet.find(:all, :offset => 50, :limit => 10) - 使用offset 跳過前 50 行。
$ rake db:migrate - 透過執行<app>/db/migrate 中的指令碼遷移到最新級別<app>/db/migrate. 注意:遷移指令碼是透過script/generate model <mod-name>
$ rake - 執行所有測試。
$ rake test:functionals - 執行功能測試,測試控制器。
$ rake test:units - 執行單元測試,測試模型。
$ test/functional/<name>_controller_test.rb - 執行一個功能測試。
$ rake doc:app - 為應用程式生成Ruby 文件。文件放在<app>/doc/app/index.html.
$ rake log:clear - 刪除所有日誌。
$ rake tmp:clear - 刪除臨時檔案。
$ script/server - 啟動此應用程式的 Web 伺服器。預設情況下,伺服器在開發模式下執行。預設情況下,它可以在以下 Web 地址訪問:https://:3000/
$ RAILS_ENV=test script/server - 在測試模式下啟動 Web 伺服器。
$ script/server -e test - 在測試模式下啟動 Web 伺服器。
$ script/server -e production - 在生產模式下啟動 Web 伺服器(更多快取等)。
some_number.to_s - 每個 Fixnum 都有方法.to_s將其轉換為字串。
一些我總是試圖記住的有用的 shell 命令
grep -r hello . - 執行 grep,在從當前目錄開始的樹中的每個檔案中搜索“hello”。
tar -cvzf archive.tgz <targ_directory> - 將目錄打包並使用 gzip 壓縮。