Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- # id:integer name:string deleted:boolean
- has_many :posts
- end
- class Post < ActiveRecord::Base
- # id:integer user_id:integer content:string deleted:boolean
- belongs_to :user
- end
- class Post < ActiveRecord::Base
- # id:integer user_id:integer content:string deleted:boolean
- belongs_to :user
- def administrated_content
- if !self.deleted
- self.content
- else
- "This post has been removed"
- end
- end
- end
- class State
- #id:integer #deleted:boolean #deleted_by:integer
- belongs_to :user
- belongs_to :post
- end
- class Post < ActiveRecord::Base
- scope :not_deleted, lambda { where(deleted_at: nil) }
- scope :deleted, lambda { where("#{self.table_name}.deleted_at IS NOT NULL") }
- def destroy
- self.update_attributes(deleted_at: DateTime.current)
- end
- def delete
- destroy
- end
- def deleted?
- self.deleted_at.present?
- end
- # ...
- # lib/extensions/act_as_fake_deletable.rb
- module ActAsFakeDeletable
- # override the model actions
- def delete
- self.update_attributes(:deleted_at, DateTime.current)
- end
- def destroy
- self.update_attributes(:deleted_at, DateTime.current)
- end
- # define new scopes
- def self.included(base)
- base.class_eval do
- scope :deleted, where('deleted_at IS NOT NULL')
- scope :not_deleted, where('deleted_at IS NULL')
- scope :destroyed, where('deleted_at IS NOT NULL')
- scope :not_destroyed, where('deleted_at IS NULL')
- end
- end
- end
- class ActiveRecord::Base
- def self.act_as_fake_deletable(options = {})
- alias_method :destroy!, :destroy
- alias_method :delete!, :delete
- include ActAsFakeDeletable
- options = { field_to_hide: :content, message_to_show_instead: "This content has been deleted" }.merge!(options)
- define_method options[:field_to_hide].to_sym do
- return options[:message_to_show_instead] if self.deleted_at.present?
- self.read_attribute options[:field_to_hide].to_sym
- end
- end
- end
- class Post < ActiveRecord::Base
- act_as_fake_deletable
- class Book < ActiveRecord::Base
- act_as_fake_deletable field_to_hide: :title, message_to_show_instead: "This book has been deleted man, sorry!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement