精華區beta Ruby 關於我們 聯絡資訊
出自我的 Blog http://lightyror.blogspot.com/2006/09/active-record-db.html 最近遇到幾個小 Project 都是要連結到本公司主力產品的DB 當然啦,那時候沒有用 Rails 所以DB Schema 絕對不可能按照 Rails 的預設安排 但是書上有說 There is always way to overridden it. 現在就來看看怎麼 ActiveReocrd overriden 原本的預設 這裡要注意的是,如果你的舊 DB 命名沒有任何規則可言的話 請使用我這個方式 但是,如果你的舊 DB 命名方式有點規則的話 像是 table name 只是沒加 s 或是開頭都有固定的字首 那還有比較好的方式可以設定 不過那些之後再提 :p 一開始,最重要的是 table 命名,以及 primary key 的命名問題 set_table_name 'table_name' set_primary_key 'table_name_id' 只要指定這兩個就可以將 Model 連結到舊 table 了 處理relationship 的時候 要注意 class_name 以及 foreign_key 的不同 has_one :legacy_table_model , :class_name => 'legacy_class_name', :foreign_key => 'key' belongs_to :legacy_table_model , :class_name => 'legacy_class_name', :foreign_key => 'key' 通常你希望使用正常的話, has_xxxxxxx 跟 belongs_to 最好乖乖設定好 這樣正常使用上就沒問題了 -- lighty RoR 是一個介紹 lighttpd , SQLite , Ruby and Rails 的 Blog http://lightyror.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.218.90.242