【发布时间】:2016-08-25 08:50:00
【问题描述】:
我创建了一个名为Collection 的接口来保存我项目模型中的任何对象的集合。我想要这个集合而不是一个数组,因为我想要 Collection 中的其他字段。
module Collection
def self.included(klass)
klass.attr_writer :list, type: Array
klass.attr_writer :class_type, type: Class
# Other fields go in here, along with their validations
klass.validate :validate_list
def validate_list
self.list.each { |o|
if(!o.instance_of? self.class_type)
klass.errors.add :list, 'Objects in list must be of the same type'
return
end
}
end
end
end
我想用这个Collection 来保存 Models::Company 的对象列表,除了我将来会添加到 Portfolio Model 的其他列表。我希望这份公司名单只是投资组合模型的一部分。
class Portfolio
include Model::Collection
@schema = {
'type' => 'object',
'properties' => {
'id' => { 'type' => 'string' },
'title' => { 'type' => 'string' },
'description' => { 'type' => 'string' },
'companies_list' => {'type' => '?'}, # 1. Should this be array or Collections?
}
}
@modelName = 'portfolios'
@collectionName = 'portfolios'
store_in collection: 'portfolios'
field :title, type: String
field :description, type: String
field :companies_list, type: Array # 2. Should this be array or array of Collections?
embeds_many :companies
end
感谢任何帮助。
【问题讨论】:
-
在模块中使用“抽象”一词确实会让人感到困惑。这有一个特定的含义,它与类有关,尽管 Ruby 根本没有真正使用这个术语,因为没有表达抽象基类的标准方法。也不清楚这里的问题是什么。
-
@tadman:对不起,我应该把它改成
class? -
不,我的意思是它是一个 mixin 模块很好,但称它为“抽象”是一种误导。为什么不叫它
Model::CollectionMethods或Model::CollectionValidations或类似的名称? -
啊,明白了。完毕。我称它为
collections,因为它既有方法又有字段。可以吗?
标签: ruby activerecord interface sinatra