Mike Mangino
2007-May-10 22:31 UTC
Counterintuitive behavior in ActiveRecord I was implementing dirty checking for an application, and I found something that is a little counterintuitive. Let me start with a quick quiz: bob=User.find(1) alice=User.find(2) trip=Trip.new trip.driver=bob old_driver=trip.driver trip.driver=alice In this example, who is old_driver? If you guessed Alice, you''re right. Inside associations.rb, the mutator is defined as: define_method("#{reflection.name}=") do |new_value| association = instance_variable_get("@#{reflection.name}") if association.nil? association = association_proxy_class.new(self, reflection) end association.replace(new_value) By re-using the proxy, we get this odd assignment behavior. Is there any reason not to create a new proxy on assignment? Simply eliminating the if condition
I was implementing dirty checking for an application, and I found
something that is a little counterintuitive. Let me start with a
quick quiz:
bob=User.find(1)
alice=User.find(2)
trip=Trip.new
trip.driver=bob
old_driver=trip.driver
trip.driver=alice
In this example, who is old_driver? If you guessed Alice, you''re right.
Inside associations.rb, the mutator is defined as:
define_method("#{reflection.name}=") do |new_value|
association =
instance_variable_get("@#{reflection.name}")
if association.nil?
association = association_proxy_class.new(self,
reflection)
end
association.replace(new_value)
By re-using the proxy, we get this odd assignment behavior. Is there
any reason not to create a new proxy on assignment?
Simply eliminating the if condition fixes my case, and all tests
still pass.
I can create a ticket with tests and a patch if I''m not missing
something here.
Mike
http://www.elevatedrails.com
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To post to this group, send email to rubyonrails-core@googlegroups.com
To unsubscribe from this group, send email to
rubyonrails-core-unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---
Apparently Analagous Threads
- Assigning to the foreign key on a belongs_to association
- Possible bug
- Dial(${PJSIP_DIAL_CONTACTS(Alice)} & ${PJSIP_DIAL_CONTACTS(Bob)}) how not to fail if one endpoint has no registered AOR?
- Counterintuitive use of LLVMBool in C-API?
- Best practices: a little pop-quiz on my blog
