mirror of
https://github.com/github/rails.git
synced 2026-02-04 03:05:27 -05:00
Support for updating a belongs to association from the foreign key (without saving and reloading the record)
Signed-off-by: Michael Koziarski <michael@koziarski.com> [#142 state:committed]
This commit is contained in:
committed by
Michael Koziarski
parent
646b5bfa61
commit
fcf31cb752
@@ -1237,7 +1237,7 @@ module ActiveRecord
|
||||
|
||||
association = instance_variable_get(ivar) if instance_variable_defined?(ivar)
|
||||
|
||||
if association.nil? || force_reload
|
||||
if association.nil? || !association.loaded? || force_reload
|
||||
association = association_proxy_class.new(self, reflection)
|
||||
retval = association.reload
|
||||
if retval.nil? and association_proxy_class == BelongsToAssociation
|
||||
@@ -1266,6 +1266,13 @@ module ActiveRecord
|
||||
end
|
||||
end
|
||||
|
||||
if association_proxy_class == BelongsToAssociation
|
||||
define_method("#{reflection.primary_key_name}=") do |target_id|
|
||||
instance_variable_get(ivar).reset if instance_variable_defined?(ivar)
|
||||
write_attribute(reflection.primary_key_name, target_id)
|
||||
end
|
||||
end
|
||||
|
||||
define_method("set_#{reflection.name}_target") do |target|
|
||||
return if target.nil? and association_proxy_class == BelongsToAssociation
|
||||
association = association_proxy_class.new(self, reflection)
|
||||
|
||||
@@ -47,6 +47,19 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
|
||||
assert_equal apple.id, citibank.firm_id
|
||||
end
|
||||
|
||||
def test_foreign_key_assignment
|
||||
# Test using an existing record
|
||||
signals37 = accounts(:signals37)
|
||||
assert_equal companies(:first_firm), signals37.firm
|
||||
signals37.firm_id = companies(:another_firm).id
|
||||
assert_equal companies(:another_firm), signals37.firm
|
||||
|
||||
# Test using a new record
|
||||
account = Account.new
|
||||
account.firm_id = companies(:another_firm).id
|
||||
assert_equal companies(:another_firm), account.firm
|
||||
end
|
||||
|
||||
def test_no_unexpected_aliasing
|
||||
first_firm = companies(:first_firm)
|
||||
another_firm = companies(:another_firm)
|
||||
|
||||
@@ -182,6 +182,18 @@ class AssociationProxyTest < ActiveRecord::TestCase
|
||||
assert_nil p.author.reset
|
||||
end
|
||||
|
||||
def test_reset_loads_association_next_time
|
||||
welcome = posts(:welcome)
|
||||
david = authors(:david)
|
||||
author_assoc = welcome.author
|
||||
|
||||
assert_equal david, welcome.author # So we can be sure the test works correctly
|
||||
author_assoc.reset
|
||||
assert !author_assoc.loaded?
|
||||
assert_nil author_assoc.target
|
||||
assert_equal david, welcome.author
|
||||
end
|
||||
|
||||
def test_reload_returns_assocition
|
||||
david = developers(:david)
|
||||
assert_nothing_raised do
|
||||
|
||||
Reference in New Issue
Block a user