MongoMapper 带有自定义用户数据的动态EmbeddedDocument

发布于 2024-12-15 05:23:53 字数 499 浏览 2 评论 0原文

我有一个名为 LogInfo 的 MongoMapper 模型,它已经定义了许多字段(:user_id、:user_key、:message 等)

但是,我还希望用户将自己的 JSON 对象嵌入为 EmbeddedDocument。

有没有办法在 MongoMapper 中使用匿名对象创建自定义对象?我是否必须求助于本机 Ruby 驱动程序?最终对象看起来像这样:

{
    user_id: 393,
    user_key: "kdIekHG32Je",
    message: "Application error",
    custom_data: {
        browser: "Firefox 8.0",
        location: {
             lat: 34.323,
             lon: -14.091
        }
    }
}

其中 custom_data 字段是应用程序用户可以提供的随机内容。

I have a MongoMapper model called LogInfo that has a number of fields already defined (:user_id, :user_key, :message, etc)

However, I'd also like the user to embed their own JSON objects as an EmbeddedDocument.

Is there a way to use anonymous objects to create a custom object in MongoMapper? Would I have to resort to the native Ruby driver instead? The final object would look something like this:

{
    user_id: 393,
    user_key: "kdIekHG32Je",
    message: "Application error",
    custom_data: {
        browser: "Firefox 8.0",
        location: {
             lat: 34.323,
             lon: -14.091
        }
    }
}

where the custom_data field is something random the app user can provide.

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

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

发布评论

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

评论(1

标点 2024-12-22 05:23:53

当然。您不必求助于 Ruby 驱动程序。

MongoMapper 通过调用将对象转换为 MongoDB 表示:

ObjectClass.to_mongo(object_instance)

to_mongo 方法已经为一堆标准类定义,您也可以为自己的类定义它。请参阅 lib/mongo_mapper/extensions 了解所有具有 < code>to_mongo 定义并 http://mongomapper.com/documentation/types.html 有关自定义类型的文档。

但是,如果您满足于让用户只给您一个哈希值,那么它就会起作用。

class LogEntry
  include MongoMapper::Document
  key :custom_data, Hash
end

Sure. You don't have to resort to the Ruby driver.

MongoMapper turns objects into a MongoDB representation by calling:

ObjectClass.to_mongo(object_instance)

The to_mongo method is already defined for a bunch of standard classes, and you can define it for your own classes too. See lib/mongo_mapper/extensions for all the classes that have to_mongo defined and http://mongomapper.com/documentation/types.html for the documentation on custom types.

BUT, if you're content to let your users just hand you a hash, it'll just work.

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