Skip to content

Instantly share code, notes, and snippets.

@djanowski
Created July 4, 2010 03:12
Show Gist options
  • Save djanowski/463067 to your computer and use it in GitHub Desktop.
Save djanowski/463067 to your computer and use it in GitHub Desktop.
require "active_record"
module HasManyPreventDestroy
def has_many(association, options = {}, &extension)
before_destroy { send(association).empty? } if options.delete(:prevent_destroy)
super(association, options, &extension)
end
end
class Foo < ActiveRecord::Base
extend HasManyPreventDestroy
has_many :bars, :prevent_destroy => true
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Schema.define(:version => 0) do
create_table :foos, :force => true do |t|
t.string :name
end
create_table :bars, :force => true do |t|
t.string :name
t.integer :foo_id
end
end
require "test/unit"
class DeletesTest < Test::Unit::TestCase
def test_deletes
foo = Foo.create!
foo.bars.create!
foo.destroy
assert_not_nil Foo.find(foo.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment