【问题标题】:how to do ruby on rails relationship dependent destroy如何做 ruby​​ on rails 关系依赖破坏
【发布时间】:2015-11-01 14:38:20
【问题描述】:

http://guides.rubyonrails.org/association_basics.html

基于上面的例子,我创建了:

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

谁能指导我如何执行级联删除操作。

  1. 如果我删除一个患者,我希望删除该患者的所有约会。我需要在某处使用 dependent 关键字吗?有人可以演示如何解决这个问题。

  2. 如何删除特定患者的所有预约?

提前致谢!

【问题讨论】:

标签: ruby-on-rails ruby associations relationship dependent-destroy


【解决方案1】:
class Patient < ActiveRecord::Base
  has_many :appointments, dependent: :destroy
  has_many :physicians, through: :appointments
end

Patient.find(id).destroy

这应该适合你。确保您使用destroy 而不是delete,因为如果您使用删除,您将不会获得您期望的级联效果。

更新 2:

如果您想销毁所有约会但不销毁患者,您可以这样做:

Patient.find(id).appointments.destroy_all

【讨论】:

  • 您能否提供以下答案:如何删除特定患者的所有预约? (只是约会,不是病人)谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 2019-09-27
  • 1970-01-01
相关资源
最近更新 更多