因為Rails實在太方便了,很多東西可以不經宣告直接拿來用,他的Model幾近簡化到看不到物件屬性!!這種方便性換來的代價就是操作Model時根本不知道這個Model/ Table裡面有哪些欄位,這時候就必須自己到資料庫裡面去查。
當然了,採用Agile開發方式是一邊設計資料庫,一邊寫Code的,這其實也不是太大的困擾。萬一資料庫大起來的話,有沒有更懶惰的方式可以直接看到物件屬性欄位而不需要到資料庫去查呢?當然有。
如果Model長這樣如何呢?這是我的User Model:# == Schema Information
# Schema version: 2
# Table name: users
# id :integer(11) not null, primary key
# name :string(255)
# password :string(255)
class User < ActiveRecord::Base
def self.checkpassword(name, password)
user = find_by_name(name)
# user.password will complain if nil user.
if user != nil && user.password == password
user
end
end
end直接在Model程式碼上方就可以看到欄位註記,那是多麼美妙的事呢?這當然不是我自己去打字的,這是Annotate Models外掛的功用。
Annotate Models可以用外掛的方式加入Rails,先切換到專案目錄後,輸入以下的指令安裝起來:
script/plugin install http://svn.pragprog.com/Public/plugins/annotate_models每次建立好新的Table,需要把註記加到Model的時候,請先切換到專案目錄,並輸入以下的指令:
rake annotate_models如此一來,就會自動將資料庫欄位註記寫到對應的Model檔以及Fixture檔裡頭,這樣一來要操作欄位以及補測試資料都非常方便。
