Rails :dependent => :destroy VS :dependent => :delete_all

Rails :dependent => :destroy VS :dependent => :delete_all

Asked on January 2, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    A :delete_all is directly in  application and deletes by SQL :

    DELETE * FROM users where compagny_id = XXXX
    

    The :destroy is instantiation  destroy it  each has their own :dependent, its callbacks can be called.

    Answered on January 2, 2019.
    Add Comment

    In Rail :dependent option following three forms:

    • :destroy/:destroy_all The associated objects are destroyed alongside this object by calling their destroy method
    • :delete/:delete_all All associated objects are destroyed immediately without calling their :destroy method
    • :nullify All associated objects’ foreign keys are set to NULL without calling their save
    Answered on January 2, 2019.
    Add Comment

    Destroy delete  associated elements where delete_all can delete multiple data from self table as DELETE * FROM table where field = ‘xyz’

    :Dependent

    Rails executes callbacks in order.  similar callbacks may affect the :dependent behavior, and the :dependent behavior may affect other callbacks

    • :destroy causes all the associated objects to also be destroyed.
    • :delete_all causes all the associated objects to be deleted directly from the database.
    • :nullify causes the foreign keys to be set to NULL. Callbacks are not executed.
    • :restrict_with_exception causes an exception to be raised if there are any associated records.
    • :restrict_with_error causes an error to be added to the owner if there are any associated objects.
    • Using with the :through option, the association on the join model must be a belongs_to, and the records which get deleted are the join records, rather than the associated records.

     

    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.