【问题标题】:Adding and removing from a has_many :through relation从 has_many :through 关系中添加和删除
【发布时间】:2010-12-11 14:32:43
【问题描述】:

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

删除或销毁的代码呢?另外,如果一个 Patient 不再存在于 Appointment 表中,它会被销毁吗?

【问题讨论】:

    标签: ruby-on-rails activerecord many-to-many has-many-through


    【解决方案1】:

    在您创建约会的代码中,不需要第二行,并且使用#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
    

    【讨论】:

    • 谢谢,我认为删除预约也会将医生从患者身上移除,反之亦然?
    • 不,除非您将:dependency =&gt; :destroy 添加到belongs_to,否则不会。
    • 实际上:dependency 设置只是在模型中添加了一个 before_destroy 钩子。如果没有这个,销毁模型记录时不会影响其他模型。
    猜你喜欢
    • 2014-06-03
    • 2015-07-31
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多