In an ActiveRecord::Base model, I can reset the state of the model to what it was when I got it from the database with reload, as long as the attribute I’m setting maps to a table column:
user = User.first
user.email #=> "email@domain.com"
user.email = "example@site.com"
user.email #=> "example@site.com"
user.reload
user.email #=> "email@domain.com"
But if I add a custom attribute, the only way I’ve found to have it act the same is like this:
class User < ActiveRecord::Base
attr_accessor :user_agent
def reload
super
self.user_agent = nil
self
end
end
My question is, is there some API to make non-database-column-attributes reset on reload? Something like:
class User < ActiveRecord::Base
# this
reloadable_attr_accessor :user_agent
# or this
def user_agent
@user_agent
end
def user_agent=(value)
set_instance_var_that_resets_on_reload("@user_agent", value)
end
end
Does that exist in Rails somewhere?
ActiveRecord does not provide a way to do this, it can only acts on the model attributes.
That being said, I think a more elegant way to do it would be to loop over the ivars and set them to whatever you like :
Note that we skip @attributes because AR is taking care of it when you reload the attributes.