通过关联添加到has_many而不查找对象

时间:2016-12-17 03:24:02

标签: ruby-on-rails has-many-through

以下是典型的has_many :through关联:

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

问题

医生与患者预约4次:[1, 2, 3, 4]

我可以通过找到用户来添加:

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

但我希望直接添加ID

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

1 个答案:

答案 0 :(得分:0)

您可以使用ID添加:

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