如何更新/销毁集合中所有文档内的一个嵌入文档

时间:2013-02-16 18:39:24

标签: ruby-on-rails mongoid

我的应用程序模型允许患者拥有CustomFields。所有患者都有相同的关税领域。海关字段嵌入在患者文档中。我应该能够添加,更新和删除自定义字段,并将此类操作扩展到所有患者。

class Patient
  include Mongoid::Document
  embeds_many :custom_fields, as: :customizable_field

  def self.add_custom_field_to_all_patients(custom_field)
    Patient.all.add_to_set(:custom_fields, custom_field.as_document)
  end

  def self.update_custom_field_on_all_patients(custom_field)       
    Patient.all.each { |patient| patient.update_custom_field(custom_field) }
  end

  def update_custom_field(custom_field)
    self.custom_fields.find(custom_field).update_attributes({ name: custom_field.name, show_on_table: custom_field.show_on_table } )
  end

  def self.destroy_custom_field_on_all_patients(custom_field)
    Patient.all.each { |patient| patient.remove_custom_field(custom_field) }
  end    

  def remove_custom_field(custom_field)
    self.custom_fields.find(custom_field).destroy
  end
end

class CustomField
  include Mongoid::Document

  field :name,          type: String
  field :model,         type: Symbol
  field :value,         type: String
  field :show_on_table, type: Boolean, default: false

  embedded_in :customizable_field, polymorphic: true
end

所有pacients都嵌入了相同的关税字段。添加自定义字段非常有效。我的疑问是关于更新和破坏。

这很有效,但速度很慢。它为每个pacient进行查询。理想情况下,我只能告诉MongoDB使用 id 更新文档,该文件嵌入在 Patient 集合中的所有文档的数组* custom_fields *中。同意毁灭。

我怎样才能在Mongoid中这样做?

我正在使用Mongoid 3.1.0& Rails 3.2.12

1 个答案:

答案 0 :(得分:0)

我认为有一种方法可以通过嵌入式文档提高效率。

也许您应该考虑在模型之间建立引用关系,以便可以在集合中使用delete_allupdate_all方法。