There is function of attributes_name in Active record by which I can check the keys of an object but I can check the blank keys for of an object which is of MongoID not of ActiveRecord, When I try t开发者_开发百科his I got the following response
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"]
It only show the attributes which are not nill , How can I check all the attributes even which are nil ? I actually wanted to make function which needs to use user.attributes.keys.include?('name')
Probably you want fields
. Attributes is more or less related to what you got from db, fields is what you defined in your model. Following works for me:
User.fields.keys
User.first.fields.keys
User.attributes.keys
worked with me but you can try columns
User.columns.map(&:name)
To get the keys in the same order as the columns in the db I used this on Rails 3.2 Ruby 1.8.7:
User.content_columns.collect{|c| c.send(:name)}
my particular use was achieved from a variable with an array of objects
@objects.first.class.content_columns.collect{|c| c.send(:name)}
精彩评论