【发布时间】:2011-03-22 22:36:14
【问题描述】:
假设我有基础模型类Item
class Item
include Mongoid::Document
field :category
end
每个类别确定项目应包含哪些字段。例如,“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 上实现这种多态性?
请向 cmets 询问所需的详细信息。
【问题讨论】:
-
"请向 cmets 询问所需的详细信息。" ?作业?
-
否 :) 有意简化了任务。
-
好的,这是工厂模式的 101 版本。从数据库加载对象,检查“类别”并产生该类型的对象。 Ruby 和其他动态语言可能非常适合这一点。问题是,我不确定 Rails 是否真的会喜欢这个。这真的适用于 ActiveRecord 吗?
-
我使用的是 mongoid,而不是 ActiveRecord。我意识到 ruby 作为动态语言为我提供了构建动态类型对象的所有工具。我也想知道 Rails 是否会喜欢它。
标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid