GGizmos
GGizmos

Reputation: 3775

How to get a synthetic attribute into the activerecord hash?

I would like to know if its possible to get a couple of synthetic attributes into the activerecord hash so of a statement like

Person.first.to_json

will include these synthetic attributes. I tried using this code in the model:

attr_accessor :foo

def foo
   return ... #some calculated value
end

And while that works fine when used on a model object, the value "foo" does not show up in the attributes hash or the json representing the object.

Upvotes: 0

Views: 147

Answers (2)

max
max

Reputation: 101976

You can use as_json to get a hash for serialization. The methods option lets you include additional methods:

class Person
  def to_json
    as_json(methods: :foo).to_json
  end
end

This is what is used when you call render json:.

But usually its better to use a serialization layer such as ActiveModel::Serializers or jBuilder. This is basically views - but that generate JSON instead of HTML.

Handling serialization on the model level just shoves more into what already amounts to mini god classes and makes things really tricky when you need different serialisations based on the context.

Upvotes: 1

Bustikiller
Bustikiller

Reputation: 2498

This method in your Person class should do the trick:

  def to_json
    original_json = JSON.parse(super)
    original_json['my_custom_key'] = do_something()
    original_json.to_json
  end

This code basically invokes the original method with super, which returns a string. Then converts that string back to a hash, and adds the extra values. After that, converts the hash to string with the to_json method, in order to hold the same interface as the original method for consistency.

Upvotes: 0

Related Questions