Rails: :dependent => :protect plugin

Ver esta página en español

Rails’ has_many has an option named :dependent which lets you specify how the delete operation affects associated records of the has_many relation. The :dependent option takes several values: :destroy, :delete, :nullify and false (or nil). But no value lets you specify that the record should not be destroyed if it still has associated records.

:dependent => :protect plugin adds a new value to the :dependent option named :protect which prevents destroying a record if it still has some associated records. If you try to destroy a record with associated record it will raise a ActiveRecord :: ReferentialIntegrityProtectionError with information about the record and the association which triggered it.

The :protect value tries to mimic the ON DELETE RESTRICT SQL statement forgot by Rails development team.

The last version of the plugin has been tested in Rails 2.1.0, 2.0.2 and 1.2.6. Previous versions of the plugin worked with Rails 1.1, but I don’t know if that hold true for the newer versions.

The code for the plugin is based on the idea and the code from Diego Algorta (diego.algorta@gmail.com) patch in Ruby on Rails ticket #3837.

This plugin will have not been possible without the help from The Complete Guide to Rails Plugins – Part I and Part II and some test code from acts_as_state_machine plugin from Scott Barron.

Installation

You can download the plugin from:

You can use script/plugin install url to install it in your Rails project.

The formal documentation for the plugin can be found at Dependent Protect documentation (not much to see there, though).

Author

Daniel Rodríguez Troitiño <drodrigueztroitino@yahoo.es> (based on the ideas and the code from Diego Algorta <diego.algorta@gmail.com>).

License

This work is released under the MIT License.

Tu servidor sin límites: 20GB de espacio, 1TB de transferencia, 1 dominio gratuito. Por 1.5€ al mes utilizando el código "RUIDOBLANCO" en DreamHost. Más información.