gpt4 book ai didi

ruby-on-rails - 从has_many :through relation中添加和删除

转载 作者:行者123 更新时间:2023-12-04 18:15:26 26 4
gpt4 key购买 nike

从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?

删除或销毁的代码呢?另外,如果“患者”不再存在于“约会”表中,会被销毁吗?

最佳答案

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

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

要销毁约会记录,您只需找到并销毁即可:
@appo = @physician.appointments.find(1)
@appo.destroy

如果要销毁约会记录并销毁患者,则需要在has_many中添加:dependency设置:
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments, :dependency => :destroy
end

关于ruby-on-rails - 从has_many :through relation中添加和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4415446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com