class ArchiveCategory include Mongoid::Document field :category_id, type: String field :sort_number, type: Integer after_initialize do |record| if(!record.new_record? && record.sort_number.class != Fixnum) record.sort_number = 0 record.save elsif(!record.new_record?) @category = Category.find(record.category_id) rescue nil if !@category.nil? @sort_number = @category.sort_number rescue nil if !@sort_number.nil? record.sort_number = @sort_number record.save end else record.destroy end end end after_save do |record| @category = Category.find(record.category_id) rescue nil if !@category.nil? @sort_number = record.sort_number rescue nil if !@sort_number.nil? if !@category.attributes[:sort_number].nil? @category.sort_number = @sort_number @category.save end end end end end