According to this post, to make attributes stick during to_json call, we need to do something like this:
def attributes
super.merge('foo' => self.foo)
end
With my beginner's knowledge in Ruby, I fail to understand the following:
attribute method present for every Ruby class?super.merge doing here? Which hashmap does it append its argument to?Hi attributes is a method provided by ActiveRecord. If you click on source you will notice how it really just exposes the instance variable @attributes which is a hash (as it can be nil it is enforced to a hash through .to_hash).
class ActiveRecord::Base
def attributes
@attributes.to_hash
end
end
We'll call this method parent as we will extend its behaviour in our class. This is possible through inheritance:
class Person < ActiveRecord::Base
def attributes
super.merge('foo' => self.foo)
end
end
attributes is now calling the parent's method [Activerecord::Base].attributes and is adding a new key to the hash.
This code is roughly equivalent and should be easier to read.
class Person < ActiveRecord::Base
def attributes
attrs = super # eg. { name: "x", created_at: [...], [...] }
attrs[:foo] = self.foo # eg. { name: "x", foo: [...], ... }
attrs
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With