在Rails Guide for associations' has_many section中有以下示例:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, through: :appointments
end
可以通过API管理连接模型的集合。例如,如果您指定
physician.patients = patients
为新关联的对象创建了新的连接模型,如果有一些已经删除,则会删除它们的行。&#34;
我想明白:
1)physician.patients = patients
行在哪里出现?
2)被分配到patients
的{{1}}是谁?
答案 0 :(得分:3)
physician.patients = patients
可能发生在控制器或模型中。patients
是您在调用上述作业之前可以创建的Patient
对象列表。在控制台中尝试:
> patient1 = Patient.create(...) # Pass appropriate parameters
> patient2 = Patient.create(...) # Pass appropriate parameters
> patients = [patient1, patient2]
> physician = Physician.create(...) # Pass appropriate parameters
> physician.patients = patients
> physician.patients.count
=> 2