Skip to content

Commit

Permalink
Do not create useless database transaction when building has_one as…
Browse files Browse the repository at this point in the history
…sociation.
  • Loading branch information
bogdan committed Nov 10, 2012
1 parent a002442 commit 3cb0f3f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
9 changes: 9 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,5 +1,14 @@
## Rails 4.0.0 (unreleased) ##

* Do not create useless database transaction when building `has_one` association.

Example:

User.has_one :profile
User.new.build_profile

*Bogdan Gusiev*

* :counter_cache option for `has_many` associations to support custom named counter caches.
Fix #7993

Expand Down
Expand Up @@ -28,7 +28,7 @@ def replace(record, save = true)
# If target and record are nil, or target is equal to record,
# we don't need to have transaction.
if (target || record) && target != record
reflection.klass.transaction do
transaction_if(save) do
remove_target!(options[:dependent]) if target && !target.destroyed?

if record
Expand Down Expand Up @@ -90,6 +90,14 @@ def remove_target!(method)
def nullify_owner_attributes(record)
record[reflection.foreign_key] = nil
end

def transaction_if(value)
if value
reflection.klass.transaction { yield }
else
yield
end
end
end
end
end
Expand Up @@ -206,6 +206,12 @@ def test_successful_build_association
assert_equal account, firm.account
end

def test_build_association_dont_create_transaction
assert_no_queries {
Firm.new.build_account
}
end

def test_build_and_create_should_not_happen_within_scope
pirate = pirates(:blackbeard)
scoped_count = pirate.association(:foo_bulb).scope.where_values.count
Expand Down

0 comments on commit 3cb0f3f

Please sign in to comment.