On Oct 29, 2011, at 5:40 AM, Michael Q wrote:

> What is the most DRY way to prevent deletion of a parent if children exist?
> 
> I assume it would be a 
> before_destroy :check_that_no_child_exists
> 
> But an object might have several different types of children and we would 
> ideally want to iterate through all the has_many's with just one command.
> 
> Is there an elegant way of doing this, and returning a helpful error message 
> indicating which type of child exists?
> 
> I'm amazed that Rails still doesn't seem to have a default facility for this 
> as its a very basic requirement.

Rails 3 added the :restrict option for dependent associations - to use it:

has_many :foos, :dependent => :restrict

Attempting to delete a model that still has associated foos will raise an 
ActiveRecord::DeleteRestrictionError with the message:

"Cannot delete record because of dependent #{reflection.name}"

You'll need to catch this exception (probably in your controller) and figure 
out how to present it to the user.

DB-level constraints are certainly another option - note that you may need to 
change the default schema format to :sql to be able to test them. You'll still 
have to catch the exception, but it will be a database-specific one.

Finally, you can prevent users *seeing* the delete option by adding code like 
this to the model:

def destroy_permitted?
  foos.empty?
end

This will remove Rapid-generated delete buttons from your interface, and 
attempting to delete a record will raise a PermissionDeniedError.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Hobo 
Users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/hobousers?hl=en.

Reply via email to