Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discard record on has_many through #43

Closed
lostie opened this issue Jan 16, 2019 · 3 comments
Closed

Discard record on has_many through #43

lostie opened this issue Jan 16, 2019 · 3 comments

Comments

@lostie
Copy link

lostie commented Jan 16, 2019

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) 
@lostie
Copy link
Author

lostie commented Jan 16, 2019

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

@bo-oz
Copy link

bo-oz commented Jan 19, 2019

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

@jarednorman
Copy link
Collaborator

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants