has_many through association dependent destroy under condition of who called destroy

后端 未结 2 780
故里飘歌
故里飘歌 2020-12-15 13:40

Is there a way to check, within a before_destroy hook, what object (class) called destroy?

In the following example, when a patient

相关标签:
2条回答
  • 2020-12-15 14:07

    Note that dependent: :destroy on a has_many :through relationship only deletes the association and not the associated record (i.e. the join records will be deleted, but the associated records won't). So if you delete a patient it will only delete the appointment and not the physician. Read the detailed explanation in the API docs.

    I have pasted the relevant paragraphs below.

    What gets deleted?

    There is a potential pitfall here: has_and_belongs_to_many and has_many :through associations have records in join tables, as well as the associated records. So when we call one of these deletion methods, what exactly should be deleted?

    The answer is that it is assumed that deletion on an association is about removing the link between the owner and the associated object(s), rather than necessarily the associated objects themselves. So with has_and_belongs_to_many and has_many :through, the join records will be deleted, but the associated records won’t.

    This makes sense if you think about it: if you were to call post.tags.delete(Tag.find_by_name('food')) you would want the food tag to be unlinked from the post, rather than for the tag itself to be removed from the database.

    0 讨论(0)
  • 2020-12-15 14:10

    Just say:

    class Physician < ActiveRecord::Base
      has_many :appointments, dependent: :restrict_with_exception
      has_many :patients, through: :appointments
    end
    

    Note the dependent: :restrict_with_exception. This will cause Active Record to refuse to destroy any Physician records that have associated Appointment records.

    See the API docs and the association basics guide.

    0 讨论(0)
提交回复
热议问题