加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 添加和删除has_many:through关系

发布时间:2020-12-17 03:26:46 所属栏目:百科 来源:网络整理
导读:从Rails协会指南中,他们使用has_many演示了多对多关系:通过如下: class Physician ActiveRecord::Base has_many :appointments has_many :patients,:through = :appointmentsendclass Appointment ActiveRecord::Base belongs_to :physician belongs_to :p
从Rails协会指南中,他们使用has_many演示了多对多关系:通过如下:

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

如果要销毁约会记录以及销毁患者,则需要将:dependency设置添加到has_many:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读