Rails 中 MongoDB 的字段数量可变
我想对可以在运行时更改的电子商务产品属性进行建模。
例如,在“创建产品”页面上,用户添加具有以下属性的特定产品:颜色、尺寸。然后添加一些具有不同属性的其他产品:分辨率、对角线尺寸。 基本上用户能够在运行时定义新属性。
如何处理产品模型中的变量属性?我习惯了关系数据库,其中每个表的字段都是预先定义的。
编辑:我正在使用 Mongoid。让我说得更具体一些。假设我有这个产品模型:
class Product
include Mongoid::Document
field :title
field :description
field :price
# attributes not known yet ???
end
模型中明确定义了产品的其他字段,但没有定义属性。也许Mongoid/MongoDB并不关心它们是否在模型中定义,而只是将它们添加到文档中?
I want to model e-commerce product attributes that can be changed in run-time.
So for example, on the Create Product page, the user adds a certain product with attributes: color, size. And then adds some other product with different attributes: resolution, diagonal size.
Basically the user is able to define new attributes at run-time.
How do I handle variable attributes in the product model? I'm used to relational databases where the fields of each table are defined a priori.
Edit: I'm using Mongoid. Let me be more specific. Let's say I have this product model:
class Product
include Mongoid::Document
field :title
field :description
field :price
# attributes not known yet ???
end
The other fields of the product are clearly defined in the model, but not the attributes. Perhaps Mongoid/MongoDB doesn't care whether they are defined in the model or not, and just adds them in the document?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已经为你做好了。它就是有效的。添加属性并保存。
如何完成取决于您使用的适配器。
这是 MongoDB.org 上的简单设置指南。
此页面包含您使用 MongoMapper 时需要的文档。
使用 Mongoid?同样,只需设置属性(您必须像哈希一样设置和访问它们:使用
[]=
和[]
),然后保存。 动态字段!It's done for you. It just works. Add the attributes and save them.
How it's done depends on what adapter you're using.
Here's a simple guide to setting it up from MongoDB.org.
And this page has documentation you'd need if you're using MongoMapper.
Using Mongoid? Again, just set attributes (you'll have to set and access them like a hash: use
[]=
and[]
), and save it. Dynamic fields!