2013-02-16 51 views
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

回答

0

我不认为有一种方法可以做到这一点与嵌入文档了良好的效益。

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

相关问题