I ran into an interesting issue today with ActiveRecord’s becomes method and discovered that it is mutating the receiver without me knowing it.
The API docs say
“The new instance will share a link to the same attributes as the original class. So any change to the attributes in either instance will affect the other.”
However, it doesn’t say that the type attribute is changed on the receiver just by the method call.
Should the docs be updated to say that the receiver’s type attribute will be changed to the class it becomes, or should becomes be changed so that it doesn’t automatically mutate the receiver? Either option would be an easy fix, though the latter would break backwards compatibility. I am using becomes with things like form_for and content_tag_for so I’m using the new object returned by becomes as opposed to the mutated object.
Here’s an example of the undocumented behavior I was seeing:
class Parent < ActiveRecord::Base
class Child < Parent
child = Child.new
child.type # => ‘Child’
new_child = child.becomes(Parent)
child.type # => ‘Parent’
new_child.type # => ‘Parent’