Search code examples
ruby-on-railsrubyrubygemsruby-on-rails-5soft-delete

Soft Delete has_and_belongs_to_many association using discard gem


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)


Solution

  • 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:

    1. Create a migration to rename the join table.
    2. Create a new model and match the name of the table.
    3. Change 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.