具有硬编码数据的Mongoid模型

时间:2012-12-22 16:25:01

标签: ruby mongodb mongoid rack

我有一个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模型一样行为。使用缓存不是我想要的。

我希望你理解我的意思。

如何完成它?

1 个答案:

答案 0 :(得分:1)

有一个名为active_hash的伟大宝石为ActiveRecord提供此功能:将一组固定数据定义为可以引用/与正常模型相关的模型,但是将其定义在代码中并加载到内存中(不是从DB存储/检索) )。

https://github.com/zilkey/active_hash

有趣的是,由于Mongoid和ActiveRecord都有共同的ActiveModel基础,你现在可以将active_hash与Mongoid文档一起使用。

例如:

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