2011年7月26日

RoR-model的建立與資料庫的結合

在ROR中,實踐orm是利用model與資料庫結合
要利用model與資料庫結合,可以照以下步驟


1.建立與編輯modle
2.rake db:migrate RAILS_ENV=環境

注意:因為rail的慣例,model名稱必須為單數 而其migration 則為複數

ex:
model名為BLog
migration會對應到blogs
另外若是特殊的字如woman
還是會自動對應到women

1.建立model
利用rail g model Blog建立model
此時會自動生出相關文件
其中之一為 create_

2.編輯migration

會在db的migration下出現一個有create_blog名稱的檔案
用文字編輯器進去
會出現

class Blog < ActiveRecord::Migration
  def self.up

    create_table do |t|
    t.timestamps   
    end

  end

  def self.down
  end
end


加入

create_table blogs do |t|
    t.string :name
    t.string :content
    t.timestamps
end



完成後打入
rake db:migrate RAILS_ENV=production
(如果是test環境則用test)

成功後即可在資料表用Blog.new直接操作

rails c
進到指令界面去操作
可以接觸資料庫後 就可以建立controller來讀取了

沒有留言:

張貼留言