1
我的應用程序模型允許患者擁有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:'更新文檔,該文檔嵌入在數組* custom_fields *中,用於集合中的所有文檔'。同爲摧毀。
我怎麼在Mongoid中做到這一點?
我使用Mongoid 3.1.0 &的Rails 3.2.12