获取MongoMapper模型的密钥

时间:2011-07-19 14:13:16

标签: ruby mongomapper

假设以下模型:

class Article
  include MongoMapper::Document

  key :name, String
  key :body, String
end

我可以将模型的密钥放入数组或散列吗?

1 个答案:

答案 0 :(得分:2)

Article.keys将为您提供关键对象的键名哈希。如果您只想要密钥名称,请尝试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"]

但请注意,如果您动态设置未在模型中声明的任何键,或者加载的对象具有不在模型中的额外键,则它们将显示在键哈希中。请参阅https://github.com/jnunemaker/mongomapper/issues/195