Reputation: 1147
What is the best way to soft delete has_and_belongs_to_many associations using Discard Gem. With this association, there is a join table in database but without actual Ruby on Rails Model.
I'll try to explain via an example, lets say there are 2 models:
class Participant < ApplicationRecord
has_and_belongs_to_many :company_employees
end
class CompanyEmployee < ApplicationRecord
has_and_belongs_to_many :participants
end
This will create company_employees_participants middle/join table in database BUT without any model in Ruby on Rails. Where i can make settings for discard gem ?
Any idea how i can solve this requirement where we need to have soft delete in joined tables using has_and_belongs_to_many assocaition in discard gem ?
discard gem: https://github.com/jhawthorn/discard
I'm using ruby 2.5.3, Rails 5.1.6, discard(1.0.0)
Upvotes: 1
Views: 901
Reputation: 716
You can take a look at paranoia gem. This gem helps you to implement the soft delete functionality. If you don't want to use the gem then you can implement it manually.
If you want to integrate manually the changes are simple:
First, you need to add migration to add the column deleted_at
as a datetime
data field type.
Then you can write scope to filter out the data the same as paranoia
gem do e.g. with_deleted
where you can check the deleted_at IS NULL
Whenever you delete any record you can set the deleted_at
.
I found one reference on StackOverflow you can refer it How to use paranoia gem in many to many association
hope it will help you
Upvotes: 0
Reputation: 4364
I don't think there's any gem that can soft delete a has_and_belongs_to_many
relationship. The best way forward would probably be to refactor your relationship and make it explicit with has_many :through
. This allows you to customize the relationship, e.g. with soft delete. The change is pretty straightforward:
has_and_belongs_to_many
to has_many :through
.You can then go ahead and follow discard's instructions to enable soft delete.
Generally speaking, I would avoid has_and_belongs_to_many
as much as possible. Sooner or later, I've always had to customize the join model and had to refactor the code. has_many :through
is just slightly more work to set up initially, but it's so much more flexible down the road that it's worth the effort.
Upvotes: 2