0

I have two models- Volunteer and Registration.

Volunteers are more stable, but Registrants will come and go. I am trying to assign a new registration to a volunteer, by having a foreign key in my Registration model for the volunteer_id.

I've looked here and here and ended up creating a join table that includes the ids of both registrations and volunteers:

class CreateJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_join_table :registrations, :volunteers do |t|
      t.index [:registration_id, :volunteer_id], name: :reg_vol_index
      t.index [:volunteer_id, :registration_id], name: :vol_reg_index
    end
  end
end

In my two models I'm not entirely sure what to list the associations as - I've read about has_many, belongs_to, and has_many_and_belongs_to- as well as t.reference.

I'm only wanting to be able to assign a volunteer id to a registration.

Can anyone help clarify what type of association is best?

Thanks in advance!

Community
  • 1
  • 1
dbate
  • 127
  • 13

1 Answers1

1

With the Join Table already created you can use has_and_belongs_to_many association for both models.

volunteer.rb:

class Volunteer < ApplicationRecord
  has_and_belongs_to_many :registrations
end

registration.rb:

class Registration < ApplicationRecord
  has_and_belongs_to_many :volunteers
end

This will allow you to access registrations through a volunteer (volunteer.registrations) and volunteers through a registration (registration.volunteers)

See here: https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Eva S.
  • 26
  • 2