61 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Ruby
		
	
	
	
			
		
		
	
	
			61 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Ruby
		
	
	
	
| class UserAttributeModel
 | |
|   
 | |
|   include Mongoid::Document
 | |
|   include Mongoid::Timestamps
 | |
|   
 | |
|   field :key
 | |
|   field :i18n_variable_id, :type => BSON::ObjectId, :index => true
 | |
|   
 | |
|   embeds_many :attribute_models
 | |
|   
 | |
|   after_update :destroy_attrs
 | |
|   
 | |
|   # Update or create the attribute_model records
 | |
|   def attribute_models=(*attrs)
 | |
|     attrs[0].each do |attributes|
 | |
|       if attributes[:id].blank?
 | |
|         attribute_models.build(attributes)
 | |
|       else
 | |
|         attribute_model = attribute_models.detect {|a| a.id.to_s == attributes[:id].to_s }
 | |
|         attribute_model.update_attributes(attributes)
 | |
|       end
 | |
|     end
 | |
|   end
 | |
|   
 | |
|   # Destroy the i18n_variables
 | |
|   def destroy_i18n_variables
 | |
|     self.i18n_variable.destroy rescue nil
 | |
|     self.attribute_models.each do |attr|
 | |
|       attr.destroy_i18n_variable
 | |
|     end
 | |
|   end
 | |
|   
 | |
|   # Update or create the i18n_variable record
 | |
|   def i18n_variable=(attr)
 | |
|     if self.i18n_variable_id
 | |
|       self.i18n_variable.update_attributes(attr) rescue nil
 | |
|     else
 | |
|       var = I18nVariable.new(attr.merge({:key => self.key, :document_class => self.class}))
 | |
|       var.save
 | |
|       self.i18n_variable_id = var.id
 | |
|     end
 | |
|   end
 | |
|   
 | |
|    # Get the i18n_variable
 | |
|   def i18n_variable
 | |
|     @i18n_variable ||= I18nVariable.find(self.i18n_variable_id) rescue nil
 | |
|   end
 | |
|   
 | |
|   protected
 | |
|   
 | |
|   # Destroy the i18n_variable for each attribute_models if marked to destroy
 | |
|   def destroy_attrs
 | |
|     attribute_models.each do |a|
 | |
|       if a.should_destroy?
 | |
|         a.destroy_i18n_variable
 | |
|       end
 | |
|     end
 | |
|   end
 | |
|   
 | |
| end
 |