【问题标题】:Understanding Rails Guide association example了解 Rails 指南关联示例
【发布时间】:2015-04-07 03:17:30
【问题描述】:

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

会为新关联的对象创建新的连接模型,如果其中一些已经消失,它们的行将被删除。”

我想了解:

1) physician.patients = patients 行在哪里出现?
2) 分配给physician.patientspatients 是谁?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:
    1. physician.patients = patients 可以发生在控制器或模型中。
    2. patientsPatient 对象的列表,您可以在调用上述分配之前创建它。

    在控制台中试试这个:

    > 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多