Get Keys of MongoMapper Model
Suppose the following model:
class Article
include MongoMap开发者_StackOverflow中文版per::Document
key :name, String
key :body, String
end
Could I get the keys of the model into an array or hash?
Article.keys
will give you a hash of key names to key objects. If you just want the key names, try Article.keys.keys
.
ruby-1.9.2-p0 :011 > Article.keys
=> {
"_id" => #<MongoMapper::Plugins::Keys::Key:0x000001041e5d48 @type=ObjectId, @name="_id", @options={}, @default_value=nil>,
"name" => #<MongoMapper::Plugins::Keys::Key:0x00000104013100 @type=String, @name="name", @options={}, @default_value=nil>,
"body" => #<MongoMapper::Plugins::Keys::Key:0x00000104011b20 @type=String, @name="body", @options={}, @default_value=nil>
}
ruby-1.9.2-p0 :012 > Article.keys.keys
=> ["_id", "name", "body"]
Watch out though, if you dynamically set any keys that aren't declared in your model, or you load an object that has extra keys that aren't in your model, they will show up in the keys hash. See https://github.com/jnunemaker/mongomapper/issues/195.
精彩评论