RUBY實踐—資料庫簡單操作

來源:互聯網
上載者:User

開發環境:

Ruby:1.9.1

Rails:2.3.5

Rake:0.8.7

Rack:1.0.1

Mysql:5.0.9

Ruby-mysql:mysql-2.8.1-x86-mswin

IDE:RubyMine2.0.1

 

資料庫準備:

database:dbdevelopment

user:crystal

password:crystal

 

一、建立Ruby項目RorTest

 

二、修改database.yml

這裡只啟用development環境資料庫,修改設定檔如下:

development:<br /> adapter: mysql<br /> encoding: utf8<br /> reconnect: false<br /> database: dbdevelopment<br /> pool: 5<br /> username: crystal<br /> password: crystal<br /> host: localhost

 

三、運行Scaffold

RorTest->New->Scaffold  運行參數:Product title:string description:string price:integer

 

 

成功運行後,將在控制台中輸出運行過程中建立的目錄及檔案(包括Model、Help、View等)

 

四、反向產生資料庫表

在db/migrate下找到類似 create_products.rb檔案,右鍵Run

 

 

成功運行後將在對應資料庫中產生schema_migrations及products資料表

 

五、修改routes.rb

在routes.rb中添加映射規則

map.connect '/products',:controller=>"product",:action=>"index"<br />map.connect ':controller/:action/:id'<br />map.connect ':controller/:action/:id.:format'

 

六、啟動伺服器,運行(http://localhost:3000/products)

 

註:Show、Edit、Destroy、New product功能可以自己測試一下,另外如果在model/product.rb中添加如下代碼,可以對product中的欄位進行必填驗證,有興趣的朋友可以測試一下

 

class Product < ActiveRecord::Base
#驗證必填項
validates_presence_of:title,:price
end

 class Product < ActiveRecord::Base<br /> #驗證必填項,message為顯示的內容,也可不填 ,如下<br /> #validates_presence_of:title,:price<br /> validates_presence_of:title ,:message=>": Please input title"<br /> validates_presence_of:price, :message=>": Please input price"<br />end

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.