Skip to content

Instantly share code, notes, and snippets.

@jondahl
Created August 18, 2009 23:56
Show Gist options
  • Save jondahl/170059 to your computer and use it in GitHub Desktop.
Save jondahl/170059 to your computer and use it in GitHub Desktop.
9 lines of code to add a :dependent => :restrict option to has_many (equivalent of "ON DELETE restrict")
when :restrict
method_name = "has_many_dependent_restrict_for_#{reflection.name}".to_sym
define_method(method_name) do
unless send(reflection.name).empty?
# change to named error...
raise ActiveRecord::StatementInvalid, "can't delete record because of dependent #{reflection.name}"
end
end
before_destroy method_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment