【发布时间】:2014-02-18 12:21:43
【问题描述】:
我正在尝试向 MongoMapper 文档动态添加键。
def build(attrs={})
doc = self.new
apply_scope(doc)
doc.set_up_keys!
doc.attributes = attrs
doc
end
def set_up_keys!
return unless form
form.fields.each do |f|
next if self.keys.include?(f.underscored_name)
self.class.send(:key, f.underscored_name, f.keys['default'].type, :required => f.required, :default => f.default)
end
end
form 是相关模型。我想根据form#fields 的内容在当前模型(self)上创建密钥。
问题是,如果我创建两个模型,它们都具有来自两个模型的相同键。
self.class.send(:key...) 将键添加到模型中。
为什么将它们添加到两个模型中?
是因为该方法是在类上下文中调用的吗?
我怎样才能只影响单个实例?
【问题讨论】:
-
不要发给班级。
-
但是#key 不是类方法吗?不确定我是否关注:(
标签: ruby metaprogramming mongomapper