在 has_many :through 关系中添加和删除

发布于 2024-10-06 23:54:13 字数 693 浏览 7 评论 0原文

从 Rails 关联指南中,他们使用 has_many :through 演示了多对多关系,如下所示:

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

我将如何创建和删除约会?

如果我有一个 @Physician,我是否需要编写如下内容来创建预约?

@patient = @physician.patients.new params[:patient]
@physician.patients << @patient
@patient.save # Is this line needed?

删除或销毁的代码怎么样?另外,如果预约表中不再存在患者,它会被销毁吗?

From the Rails associations guide, they demonstrate a many-to-many relationship using has_many :through like so:

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

How would I create and remove appointments?

If I've got a @physician, do I write something like the following for creating an appointment?

@patient = @physician.patients.new params[:patient]
@physician.patients << @patient
@patient.save # Is this line needed?

What about code for deleting or destroying? Also, if a Patient no longer existed in the Appointment table will it get destroyed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖彼岸 2024-10-13 23:54:13

在创建约会的代码中,不需要第二行,并使用 #build 方法而不是 #new

@patient = @physician.patients.build params[:patient]
@patient.save  # yes, it worked

要销毁约会记录,您只需找到它即可和销毁:

@appo = @physician.appointments.find(1)
@appo.destroy

如果您想在销毁患者的同时销毁预约记录,则需要将 :dependency 设置添加到 has_many:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments, :dependency => :destroy
end

In your code of creating an appointment, the second line is not needed, and using #build method instead of #new:

@patient = @physician.patients.build params[:patient]
@patient.save  # yes, it worked

For destroying an appointment record you could simply find it out and destroy:

@appo = @physician.appointments.find(1)
@appo.destroy

If you want to destroy the appointment records along with destroying a patient, you need to add the :dependency setting to has_many:

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments, :dependency => :destroy
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文