I have a Rails model object that has attributes maps to columns in a DB. I compute couple of temporary fields name and age which are not in the DB columns. Is there a way to merge them into the object temporarily without making changes to the model object?
class MyModel < ApplicationRecord
end
I tried using attributes.merge. and tried :
my_obj = my_obj.attributes.merge({ age: compute_age })
my_obj = my_obj.attributes.merge({ name: compute_name })
The second merge however fails with NoMethodError: undefined method `attributes' for #Hash:0x0000000120060010.
Looks like the moment I merge first one it makes the object a Hash. So I need to do
my_obj = my_obj.attributes.merge({ age: compute_age })
my_obj[:name]=compute_name
All the other properties also are accessed as a hash. However this feels inconsistent and weird to me!
Is there a better option to this than using attributes.merge i.e preserve the object? I guess it maybe cleaner to add the attr to the model object but those attributes are temporary and should not be accessed outside.