【问题标题】:Mongoid model with hardcoded data具有硬编码数据的 Mongoid 模型
【发布时间】:2012-12-22 16:25:01
【问题描述】:

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

希望你明白我的意思。

如何实现呢?

【问题讨论】:

    标签: ruby mongodb mongoid rack


    【解决方案1】:

    有一个很棒的 gem,叫做 active_hash,它为 ActiveRecord 提供了这个功能:将一组固定的数据定义为可以引用/关联到普通模型的模型,但是在代码中定义并加载到内存中(不存储/从数据库中检索) )。

    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
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2016-04-11
      相关资源
      最近更新 更多