I have several classes associated as following:
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
class Group < ActiveRecord::Base
has_many :posts, :dependent => :destroy
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :groups
Now, I want to delete Users, Groups, and Posts by setting their ‘active’ field to false and leave them in database. Initially, I was hoping that destroying a user or a group will cause destruction of their posts (delete action would set the flag to false), However as far as I understood, in such cases Ruby just breaks the corresponding association without destroying the posts. I am wondering whether it can be done nicely, or I just have to write a separate function and call it instead of regular delete?
Rather than deleting records from the database, we can retire them with just a little bit of code and configuration.
Create a new directory under your app/ directory called “concerns”.
Create a new file in this directory called “retireable.rb”.
Copy and paste the following code into it:
4) Each of your models which need this functionality must:
4a) Have the ‘
retired‘ boolean field and ‘retired_at‘ datetime field in the database schema.4b)
include Retireablemust be within the class definition for that model; i.e.5) In your ‘
config/application.rb‘, add the following line:Now calls to instance.destroy (eg. @user.destroy, @group.destroy) will be handled by retireable, therefore not deleted from the database and not breaking the association.
Hope that helps!