paranoia: soft delete model
安装和设置
#gemfile
gem 'paranoia'
#添加支架rails g scaffold article name
#model中添加方法
class Article < ApplicationRecord
acts_as_paranoid
end
#添加deleted_at字段
rails g migration add_deleted_at_to_articles deleted_at:datetime:index
#console
Article.last.destroy
Article.with_deleted.last.restore
Article.last.really_destroy!
#articles_controller.rb
@articles = Comments.with_deleted.find(params[:id])
if params[:type] == 'normal'
@comment.destroy
elsif params[:type] == 'forever'
@comment.really_destroy!
elsif params[:type] == 'undelete'
@comment.restore
end
#view
<%= link_to 'normal', comment_path(@comment, type: :normal), method: :delete, class: 'badge' %>
<%= link_to 'undelete', comment_path(@comment, type: :undelete), method: :delete, class: 'badge' %>
<%= link_to 'forever', comment_path(@comment, type: :forever), method: :delete, class: 'badge' %>
基本使用
#model中添加acts_as_paranoid和添加deleted_at字段
默认情况下,deleted_at字段是空的,若:
Article.first.destroy #数据数据库中是存在的,但是这个对象的deleted_at字段设置为当下删除时间
Article.all.size #执行上面的删除字段,size的值会减少1,就是说在view页面中,这条字段是不能显示的
Article.with_deleted.size #该语句反映的是数据库中数量的数量
Article.all.size #该语句放映的是deleted_at为空的对象的数量
Article.first.destroy #设置deleted_at字段为当前时间,view中不能显示
Article.first.really_destroy! #Article.first的返回值从数据库中删除
Article.with_deleted.first.really_destroy! #Article.with_deleted.first的返回值从数据库中删除
Article.with_deleted.first.restore #Article.with_deleted.first中deleted_at字段设置为空,view中可见。
关联用法
#article has_many comments
#需要两个model都定义acts_as_paranoid,同时两者都需要添加deleted_at:datetime:index字段
#article
class Article < ApplicationRecord
acts_as_paranoid
has_many :comments
end
#comment
class comment < ApplicationRecord
acts_as_paranoid
belongs_to article
end
#注意点:destroy会触发关联,delete不会触发关联
Article.first.comments.first.delete #不会改变Article.first.comments.first的deleted_at值
Article.first.comments.first.destroy #会改变Article.first.comments.first的deleted_at值