I have two models that I currently have as STI.
class Event
class BlockedTime < Event
class Appointment < Event
The models are similar except that ‘Appointment’ has_one ‘client’ and has_one ‘service’, whereas ‘BlockedTime’ has neither of those associations.
Additionally, I want to be able to convert between the two types easily, and when I search, I’m usually searching on both types together, not one or the other. For those reasons I hesitate to make them separate tables.
For switching between the types, I currently do this in the same form, using the parent ‘Event’ type, and storing the ‘type’ as a hidden field, but this is definitely not working out well. I have to do all sorts of conversions in the controller to check validations, etc.
How would you recommend modeling this?
So, if I were having this problem I would probably model the database differently.
Instead of a STI/Inheritance pattern, I would use a Composition pattern. So:
Controller
Form or at least part of the form
This part of the form uses
persisted?to check to see if theAppointmentobject is a new record or has been persisted to the database. Then if it has been and you want to remove it then it will throw the_destroyflag foraccepts_nested_attributes_forand delete the existingappointmentassociation to make it a freeBlockTime.Then you could include all the
Appointmentfields in this form too. You might want to cook up some javascript to disable/enable fields depending on theradio_buttonselection