2011-09-08 125 views
3

活動記錄中有屬性名稱的功能,通過該功能我可以檢查對象的鍵,但是我可以檢查MongoID不是ActiveRecord的對象的空白鍵, 當我嘗試這個I得到以下回應對象的屬性

ruby-1.9.2-p290 :001 > u = User.new 
=> #<User _id: 4e684f7771393161cc000001, _type: nil, username: nil, first_name: nil, last_name: nil, email: nil, password: nil, password_salt: nil, password_hash: nil, profile_picture: nil, facebook_id: nil, facebook_enabled: nil, facebook_access_token: nil, twitter_id: nil, twitter_enabled: nil, twitter_access_token: nil, twitter_access_secret: nil, points: nil, remember_token: nil, remember_token_expires_at: nil, active: false, activation_code: nil, activated_at: nil> 
ruby-1.9.2-p290 :002 > u.attributes.keys 
=> ["active", "_id"] 

它只顯示屬性不是nill,我怎樣才能檢查所有的屬性,哪怕是零? 我其實想做的功能就是需要使用user.attributes.keys.include?('name')

+0

我試着在一個應用程序的例子,我已經遷移到3.1昨天軌,並在那裏回答'u.attributes.keys'是屬性的散列的所有鍵。你正在使用哪個版本的Rails? – mliebelt

+0

我正在使用Rails 3.0.7 和mongoid(2.2.0,2.1.9) –

+0

我在將rails更新到3.1.0之後嘗試了它,但它仍然沒有顯示所有的鍵並只顯示那些不爲null的值,你能告訴我你的版本的mongoid和mongo寶石? –

回答

2

大概你想要fields。屬性或多或少與您從數據庫獲得的內容相關,字段是您在模型中定義的內容。以下工作對我來說:

User.fields.keys 
User.first.fields.keys 
+0

在主動記錄v4.2中不起作用 – allenwlee

1
User.attributes.keys 

與我的工作,但你可以嘗試columns

User.columns.map(&:name) 
1

要獲得相同的順序在數據庫中的列的按鍵我用這個on Rails的3.2紅寶石1.8.7:

User.content_columns.collect{|c| c.send(:name)} 

我的特殊用途是從一個變量與一個obj數組ECTS

@objects.first.class.content_columns.collect{|c| c.send(:name)}