2009-08-17 54 views
107

去年秋天我開始了我的第一個Rails應用程序,並且在支付工作時我必須在架子上放置幾個月。我現在有興趣回到項目並閱讀代碼,以找出我離開的地方。您如何在Rails中發現模型屬性

Rails在運行時動態創建模型屬性的事實可以節省大量的重複輸入,但是我發現很難輕易發現所有模型類中存在的屬性/屬性,因爲它們沒有在我的類中明確定義文件。爲了發現模型屬性,我保持schema.rb文件處於打開狀態,並在它和我正在編寫的使用模型屬性的任何代碼之間翻轉。這種方法很有效,但是笨重,因爲我必須讀取模式文件來獲取屬性,使用模型類文件來獲取方法,以及我正在編寫的任何新代碼,以調用屬性&方法。

所以我的問題是,當你第一次分析Rails代碼庫時,你如何發現模型屬性?你是否始終保持schema.rb文件處於打開狀態,還是有更好的方式,不需要在模式文件&之間不斷跳轉?

+6

感謝您的回答。這聽起來好像沒有一個好的方法來在模型源文件中聲明屬性名稱,而是保持打開一個終端並戳對象來查找它們的屬性。 – gbc 2009-08-20 20:58:08

回答

219

對於Schema相關的東西

Model.column_names   
Model.columns_hash   
Model.columns 

實例變量/屬性在AR對象

object.attribute_names      
object.attribute_present?   
object.attributes 

對於實例方法,而不繼承自父類

Model.instance_methods(false) 
+9

爲了獲得關聯,你也可以這樣做: Model.reflect_on_all_associations.map(&:name) – Filippos 2014-11-28 09:27:51

+1

在ActiveRecord 5中(可能更早),您可以調用'Model.attribute_names'。 – aceofbassgreg 2016-09-22 17:17:40

4
some_instance.attributes 

來源:blog

+0

some_class.attributes。鍵是一個小清潔 – klochner 2009-08-17 20:29:22

+0

想知道是否有任何IDE使用這個自動完成?似乎是一個明顯的事情要做的軌道模型。當我開始輸入屬性名稱並且它不自動完成時,我總是感到失望。 – frankodwyer 2009-08-17 23:27:18

+7

因爲'attributes'是一個實例方法,所以正確的代碼示例會說'some_instance.attributes'。 – RocketR 2011-12-15 12:35:32

24

有一個Rails插件叫做標註車型,這將產生對你的模型文件 這裏頂你的模型屬性是鏈接:

https://github.com/ctran/annotate_models

保持註解同步,您可以編寫任務以在每次部署後重新生成註釋模型。

+3

我認爲新網站是同一個插件,https://github.com/ctran/annotate_models – 2013-10-17 20:46:35

9

如果你只對數據庫的屬性和數據類型感興趣,可以使用Model.inspect

irb(main):001:0> User.inspect 
=> "User(id: integer, email: string, encrypted_password: string, 
reset_password_token: string, reset_password_sent_at: datetime, 
remember_created_at: datetime, sign_in_count: integer, 
current_sign_in_at: datetime, last_sign_in_at: datetime, 
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime, 
updated_at: datetime)" 

另外,已經爲你的開發環境中運行rake db:createrake db:migrate,文件db/schema.rb將包含權威人士爲您的數據庫結構:

ActiveRecord::Schema.define(version: 20130712162401) do 
    create_table "users", force: true do |t| 
    t.string "email",     default: "", null: false 
    t.string "encrypted_password",  default: "", null: false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   default: 0 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
end 
8

爲了描述模型我用下面的代碼片段

Model.columns.collect { |c| "#{c.name} (#{c.type})" } 

再次這是如果你正在看漂亮的印刷品來形容你ActiveRecord沒有你通過遷移或跳過該開發人員之前,你是足夠好的評論屬性。

+0

這非常適合打印出特定模型的所有實例的所有屬性 - 謝謝! – ConorB 2016-06-03 15:10:44