获取 MongoMapper 模型的键

发布于 2024-11-24 21:22:12 字数 159 浏览 1 评论 0原文

假设有以下模型:

class Article
  include MongoMapper::Document

  key :name, String
  key :body, String
end

我可以将模型的键放入数组或哈希中吗?

Suppose the following model:

class Article
  include MongoMapper::Document

  key :name, String
  key :body, String
end

Could I get the keys of the model into an array or hash?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨落□心尘 2024-12-01 21:22:12

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文