Skip to content

Commit

Permalink
Merge pull request #5334 from courtland/master
Browse files Browse the repository at this point in the history
Fix deleting from a HABTM join table upon destroying an object of a model with optimistic locking enabled.
  • Loading branch information
jonleighton committed Mar 30, 2012
2 parents 34320cd + 2931f41 commit 2eb1118
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 1 deletion.
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/locking/optimistic.rb
Expand Up @@ -104,6 +104,8 @@ def update(attribute_names = @attributes.keys) #:nodoc:
def destroy #:nodoc:
return super unless locking_enabled?

destroy_associations

if persisted?
table = self.class.arel_table
lock_col = self.class.locking_column
Expand Down
12 changes: 11 additions & 1 deletion activerecord/test/cases/locking_test.rb
Expand Up @@ -22,7 +22,7 @@ class ReadonlyFirstNamePerson < Person
end

class OptimisticLockingTest < ActiveRecord::TestCase
fixtures :people, :legacy_things, :references, :string_key_objects
fixtures :people, :legacy_things, :references, :string_key_objects, :peoples_treasures

def test_non_integer_lock_existing
s1 = StringKeyObject.find("record1")
Expand Down Expand Up @@ -239,6 +239,16 @@ def test_polymorphic_destroy_with_dependencies_and_lock_version
end
assert car.destroyed?
end

def test_removing_has_and_belongs_to_many_associations_upon_destroy
p = RichPerson.create!
p.treasures.create!
assert !p.treasures.empty?
p.destroy
assert p.treasures.empty?
assert RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1").empty?
end

end

class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
Expand Down
3 changes: 3 additions & 0 deletions activerecord/test/fixtures/peoples_treasures.yml
@@ -0,0 +1,3 @@
michael_diamond:
rich_person_id: <%= ActiveRecord::Fixtures.identify(:michael) %>
treasure_id: <%= ActiveRecord::Fixtures.identify(:diamond) %>
6 changes: 6 additions & 0 deletions activerecord/test/models/person.rb
Expand Up @@ -85,3 +85,9 @@ class TightPerson < ActiveRecord::Base
end

class TightDescendant < TightPerson; end

class RichPerson < ActiveRecord::Base
self.table_name = 'people'

has_and_belongs_to_many :treasures, :join_table => 'peoples_treasures'
end
5 changes: 5 additions & 0 deletions activerecord/test/schema/schema.rb
Expand Up @@ -469,6 +469,11 @@ def create_table(*args, &block)
t.references :best_friend_of
t.timestamps
end

create_table :peoples_treasures, :id => false, :force => true do |t|
t.column :rich_person_id, :integer
t.column :treasure_id, :integer
end

create_table :pets, :primary_key => :pet_id ,:force => true do |t|
t.string :name
Expand Down

0 comments on commit 2eb1118

Please sign in to comment.