在 has_many :through 关系中添加和删除
从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在创建约会的代码中,不需要第二行,并使用
#build
方法而不是#new
:要销毁约会记录,您只需找到它即可和销毁:
如果您想在销毁患者的同时销毁预约记录,则需要将 :dependency 设置添加到 has_many:
In your code of creating an appointment, the second line is not needed, and using
#build
method instead of#new
:For destroying an appointment record you could simply find it out and destroy:
If you want to destroy the appointment records along with destroying a patient, you need to add the :dependency setting to has_many: