K2x*_*2xL 5 ruby ruby-on-rails mongodb mongoid
我正在尝试将我的一些模型类扩展为"资产"类.四种类型的资产中的每一种都能够生成一个slug.set_callback(:save, :before)因此,我希望它们扩展一个具有set_callback(以及其他方法)的Asset类,而不是编写四个相同的方法. .
起初我尝试简单地让他们扩展Asset类但我遇到了问题,当我将其中一个资产保存到数据库(mongo)时,他们插入的集合称为Asset而不是他们自己的名字.
在我用Google搜索后,人们似乎建议使用模块.所以我试过了:
module Asset
field :slug, :type => String
set_callback(:save, :before) do |document|
# make document.slug = to whatever
end
end
class Video
include Mongoid::Document
include Asset
field :video_name, :type => String
field :description, :type => String
field :some_more_fields, :type => String
end
Run Code Online (Sandbox Code Playgroud)
但是当我包含资产时我遇到了一些错误:
'undefined method `field' for Asset:Module'
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用Mongoid
方法字段在Asset模块的上下文中是未知的.因此,只有在包含模块时才需要调用字段:
module Asset
def self.included(base)
base.send(:field, :slug, :type => String)
end
end
Run Code Online (Sandbox Code Playgroud)
编辑:代码块中的包装代码
| 归档时间: |
|
| 查看次数: |
1573 次 |
| 最近记录: |