Ruby on Rails 多态模型:动态字段
假设我有基本模型类 Item
class Item
include Mongoid::Document
field :category
end
每个类别确定 item 应包含哪些字段。例如,“category1”中的项目应包含名为 text
的附加字符串字段,“category2”中的项目应包含字段 weight
和 color
。所有字段都是基本类型:字符串、整数等。
这些附加值将作为文档字段存储在 mongodb 中:
> db.items.find()
{ "_id" : ObjectId("4d891f5178146536877e1e99"), "category" : "category1", "text" : "blah-blah" }
{ "_id" : ObjectId("4d891f7878146536877e1e9a"), "category" : "category2", "weight" : 20, "color" : "red" }
类别也存储在 mongodb 中。字段的配置由管理员在运行时定义。
> db.categories.find()
{ "_id" : "category1", "fields" : [ { "name" : "text", "type" : "String" } ] }
{ "_id" : "category2", "fields" : [
{
"name" : "weight",
"type" : "Integer"
},
{
"name" : "color",
"type" : "String"
}
] }
用户需要使用 html 表单来编辑项目,输入为特定项目类别定义的所有附加字段的值。
问题是
我可以采取什么方法在rails上实现这种多态性?
请询问所需的详细信息和评论。
Suppose I have base model class Item
class Item
include Mongoid::Document
field :category
end
Each category determines which fields should item contain. For example, items in "category1" should contain additional string field named text
, items in "category2" should contain fields weight
and color
. All the fields are of basic types: strings, integers and so on.
These additional values are to be stored in mongodb as document's fields:
> db.items.find()
{ "_id" : ObjectId("4d891f5178146536877e1e99"), "category" : "category1", "text" : "blah-blah" }
{ "_id" : ObjectId("4d891f7878146536877e1e9a"), "category" : "category2", "weight" : 20, "color" : "red" }
Categories are stored in the mongodb, too. Fields' configuration is defined at runtime by an administrator.
> db.categories.find()
{ "_id" : "category1", "fields" : [ { "name" : "text", "type" : "String" } ] }
{ "_id" : "category2", "fields" : [
{
"name" : "weight",
"type" : "Integer"
},
{
"name" : "color",
"type" : "String"
}
] }
Users need to edit Items with html forms entering values for all additional fields defined for the category of particular item.
The question is
What approaches could I take to implement this polymorphism on rails?
Please ask for required details with comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需对 Item 进行子类化,Mongoid 就会处理其余的事情,例如存储类型。
Rails 会喜欢它,但您可能想要使用 #becomes 方法,因为它会让表单生成器满意并且路径生成更容易:
https://github.com/romanbsd/mongoid/commit/9c2fbf4b7b1bc0f602da4b059323565ab1df3cd6
Just subclass the Item, and Mongoid will take care of rest, e.g. storing type.
Rails will like it, but you'll probably want to use #becomes method, as it will make form builder happy and path generation easier:
https://github.com/romanbsd/mongoid/commit/9c2fbf4b7b1bc0f602da4b059323565ab1df3cd6