使mongoid会话只读

我在mongoid.yml有不同的会话,其中一个会话提供来自静态mongo数据库的数据。 我想知道是否有可能在只读模式下“加载”会话,因此不能对savecreatedestroydestroy_all进行任何更改。 我的mongoid.yml看起来像这样:

 production: sessions: default: database: my_app_production hosts: - localhost:27017 options: read: primary static_content: database: static_content_db hosts: - localhost:27017 options: read: primary options: use_utc: true 

我有static_content会话的特殊模型,它们看起来像这样:

  class StaticMappings include Mongoid::Document include Mongoid::Attributes::Dynamic store_in collection: "static_mappings", session: "static_content" end 

我想防止自己形成意外调用StaticMappings.destroy_allStaticMappings.create(...) 。 这可能吗?

我发现这使用Mongoid将整个模型设为只读 ,但这不会阻止某人在模型实例上调用createdestroy

这是一个老问题,但我最近遇到了同样的问题,所以决定分享。 虽然,我想注意,这不是一个per-sesson解决方案,而是一个每个模型的解决方案。

正如我所知,有两种方法可以实现:

1.重新定义readonly?

如果您查看Mongoid代码,您会看到保存,删除或更新的所有函数都只读取readonly? 检查模型是否为只读。 没有真正记录并且有缺点 – 创建和创建! 允许在此模型上(破坏,更新,保存将不会运行)。

 private def readonly? true end 

2.自定义回调

除了之前的方法,您还可以添加回调以确保即使创建也不会通过:

 before_create :readonly_secret private def readonly? true end def readonly_secret raise Mongoid::Errors::ReadonlyDocument, self.class if readonly? end 

实际上,你可以摆脱readonly? 方法alltogether,并添加其他回调,如before_savebefore_destroybefore_updatebefore_create

操纵“读经”

如果您觉得需要从运行时代码中操作只读状态,则可以为模型的类定义属性:

 before_create :readonly_secret class << self attr_accessor :readonly end private def readonly? self.class.readonly.nil? ? true : self.class.readonly end def readonly_secret raise Mongoid::Errors::ReadonlyDocument, self.class if readonly? true end