Add to has_many through association without finding objects

40 views Asked by At

Here is a typical has_many :through association:

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

The Problem

The physician makes 4 appointments with patients: [1, 2, 3, 4]

I can add by finding the users:

user_ids = [1, 2, 3, 4]
users = User.where(id: user_ids)
@physician.patients.push(users)

But I want to add by ID directly:

user_ids = [1, 2, 3, 4]
@physician.patients.push(user_ids)
1

There are 1 answers

0
Thanh On

You can use ids to add:

user_ids = [1, 2, 3, 4]
@physician.patient_ids = user_ids