Rails 5: STI With Has Many Through Association

Viewed 1635

I have searched extensively for a solution to my situation, but I can't find anything.

In my application I have a Person model that only stores data about people:

class Person < ApplicationRecord
end

Then I have a Trial model. Trials can have many people using a has-many-through association. Additionally, in the context of a Trial, a person can be a Defendant or a Plaintiff. To achieve this, I set up my models like this:

class Trial < ApplicationRecord
  has_many :trial_people
  has_many :plaintiffs, class_name: 'Plaintiff', through: :trial_people, source: :person
  has_many :defendants, class_name: 'Defendant', through: :trial_people, source: :person
end

class TrialPerson < ApplicationRecord
  belongs_to :trial
  belongs_to :person
end

class Plaintiff < Person
end

class Defendant < Person
end

I am then using Select2 JQuery plugin to add in the defendants and plaintiffs for each trial in the view. Obtaining the IDs in strong parameters:

params.require(:trial).permit(:title, :description, :start_date, :plaintiff_ids => [], :defendant_ids => [])

So that I can do achieve like the following:

trial.defendants
trial.plaintiffs

The problem is that I do not have any way of distinguishing between those classes inside the trial_people table. I was thinking on adding a type column to that table (STI), but I do not know how to automatically add that type to each defendant or plaintiff when saving the Trial object.

Would appreciate some insight on how to achieve this, using STI or not.

1 Answers
Related