了解Rails指南关联示例

时间:2015-04-06 18:53:22

标签: ruby-on-rails associations

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}}是谁?

1 个答案:

答案 0 :(得分:3)

  1. physician.patients = patients可能发生在控制器或模型中。
  2. patients是您在调用上述作业之前可以创建的Patient对象列表。
  3. 在控制台中尝试:

    > 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