RubyChina如何实现软删除?

  1. 在model层新建一个Module
    # coding: utf-8
    # 软删除
    module Mongoid
      module SoftDelete
        extend ActiveSupport::Concern
    
        included do
          field :deleted_at, :type => DateTime
    
          default_scope where(:deleted_at => nil)
          alias_method :destroy!, :destroy
        end 
    
        def destroy
          if persisted?
            self.update_attribute(:deleted_at,Time.now.utc)
          end 
    
          @destroyed = true
          freeze
        end 
      end 
    end
    


  2. 在模型中引用这个module
      include Mongoid::SoftDelete

  3. 如果是Mysql数据库,需要定义deleted_at字段





你可能感兴趣的:(数据库,mysql,Module,include)