jhawthorn / discard

🃏🗑 Soft deletes for ActiveRecord done right

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Discard record on has_many through

lostie opened this issue · comments

If you have the following relations:

class Vehicle < ApplicationRecord  
  has_many :vehicle_parts
  has_many :parts, through: :vehicle_parts
end 

class VehiclePart < ApplicationRecord
  belongs_to :vehicle
  belongs_to :part  
end

class Part < ApplicationRecord
  has_many :vehicle_parts  
  has_many :vehicles, through: :vehicle_parts
end

How would discard be configured? Would all the table have a discarded_at column? And how are we expected to discard a part for a given vehicle, not the part itself?

Without any soft delete tool, I would be doing something like this:

vehicle = Vehicle.find(vehicle_id)
part = Part.find(part_id)
vehicle.parts.delete(part) 

Also, along the same lines, how can I get a list of kept vehicles including only kept parts?

# This only returns a list of kept vehicles, 
# some of the included parts might have already been discarded
# as the `kept` scope only applies to the vehicles table
Vehicle.includes(:parts).kept
commented

You can call the scope on parts later in your script, so suppose you want all kept parts:

Vehicle.includes(:parts).kept.parts.kept gives you all the kepts parts

@lostie If you want to discard the part for the vehicle without discarding the part itself, you'd include Discard::Model in the VehiclePart model. To fetch the parts for a vehicle you would do some_vehicle.parts.kept. To discard a part of a vehicle you would call .discard on the specific VehiclePart.