本文介绍了添加和从的has_many删除:通过关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Rails的协会指导,他们表现出使用许多一对多关系的has_many:通过像这样:

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?

如果我有一个 @physician ,我写的东西像下面创建一个约会?

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?

那么code删除或销毁?此外,如果患者在预约表不再存在将它被摧毁?

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

推荐答案

在你的$ C $创建一个约会C,第二行是不需要的,并使用 #build 方法,而不是 #NEW

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

如果你想消灭预约记录以及摧毁一个病人,你需要的补充:依赖设置的has_many:

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

这篇关于添加和从的has_many删除:通过关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:08