尝试加入两个模型,不确定适当的活动记录关联应该是什么

Trying to join two models, not sure what the appropriate active record association should be

我有两个模型——志愿者和注册。

志愿者比较多table,但注册者会来来去去。我正在尝试通过在我的注册模型中为 volunteer_id.

分配一个新注册给志愿者

我查看了 and here 并最终创建了一个连接 table,其中包括注册和志愿者的 ID:

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

在我的两个模型中,我不完全确定将关联列为什么 - 我读过 has_many、belongs_to 和 has_many_and_belongs_to- 以及 t.reference.

我只想能够为注册分配一个志愿者 ID。

谁能帮助阐明哪种类型的协会最好?

提前致谢!

在已经创建连接 Table 的情况下,您可以对两个模型使用 has_and_belongs_to_many 关联。

volunteer.rb:

class Volunteer < ApplicationRecord
  has_and_belongs_to_many :registrations
end

registration.rb:

class Registration < ApplicationRecord
  has_and_belongs_to_many :volunteers
end

这将允许您通过志愿者 (volunteer.registrations) 访问注册和通过注册访问志愿者 (registration.volunteers)

看这里:https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association