simonlehmann
simonlehmann

Reputation: 882

Store two child records for a resource - ActiveRecord | Rails

I'm working on a Rails 5.2 project that has Teacher, Student, and EmergencyContact models. I'd like to store two EmergencyContact records for each Teacher and Student record. Given that both the Teacher and Student models will share the same requirement for EmergencyContact records, I though it'd be most efficient to have the two models share the same EmergencyContact table.

Is this the best way to go? What would be the best way to set this up with ActiveRecord?

The below ERD shows the concept:

enter image description here Any help would be much appreciated.

Thanks

Upvotes: 0

Views: 54

Answers (1)

sghosh968
sghosh968

Reputation: 601

Usually for this type of requirement it is done making use of Polymorphic association in ActiveRecord. You can find more information about it here.

The setup for this would be something similar as mentioned below :

In models

# In app/models/emergency_contact.rb
class EmergencyContact < ApplicationRecord
  belongs_to :emergency_contactable, polymorphic :true
end

# In app/models/teacher.rb
class Teacher < ApplicationRecord
  has_many :emergency_contacts, as: :emergency_contactable
end

# In app/models/student.rb
class Student < ApplicationRecord
  has_many :emergency_contacts, as: :emergency_contactable
end

Schema migrations (new fields in emergency contacts table) required

class AddEmergyContactable < ActiveRecord::Migration[5.0]
  def change
    add_reference :emergency_contacts, :emergency_contactable, polymorphic: true, index: true
  end
end

Let me know if this helps.

Upvotes: 2

Related Questions