用硬编码的数据Mongoid模型
问题描述:
我有一个mongoid模型用硬编码的数据Mongoid模型
class MyMongoidModel
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
field :data_id, :type => Integer
has_and_belongs_to_many :the_other_model, :class_name => 'class_name_model'
has_many :model2
def self.all
[
#.... the hardcoded data that will never be changed
]
end
end
它使用的其他模型,它使用它们。但是,包含很长一段时间不会更改的数据,比方说,根本就没有。因此,我不想从db中检索它,我希望它被硬编码,并且同时,我想它像一个正常的mongoid模型一样行动行为。使用缓存不是我正在寻找的。
我希望你明白我的意思。
如何做到这一点?
答
有一个很好的gem叫做active_hash,它为ActiveRecord提供了这个功能:将一组固定的数据定义为模型,你可以引用/关联到普通模型,但在代码中定义并加载到内存中(不存储/ D B)。
https://github.com/zilkey/active_hash
有趣的是,因为Mongoid和ActiveRecord的都有着共同的基础上加载ActiveModel,您可以现在用Mongoid文档使用active_hash。
例如:
class Country < ActiveHash::Base
self.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]
end
class Order
include Mongoid::Document
include Mongoid::Timestamps
has_one :country
end