theog
theog

Reputation: 2092

ruby serialise a model to represent in

I have a set of legacy database tables that i cannot normalize out to what should have been done in the first place. e.g one big table with 200 columns.

I'm building an API and would like to represent this data to the consumer in a better state, and perhaps address the database issues at a later stage, there are many backend systems that reply on the data and changes are not easy.

I wanted to represent the current database schema using Active Record, however perform a model transformation into a new model that will be used for presentation only to an API consumer as json data.

current database schema: Products table (200 columns)

New Model: Product + Pricing + Assets + Locations + Supplier

I could hard-code a json string in a template, but feel that would not be a very poor approach. What approach or gem would you recommend to tackle this best?

I have looked at : RABL ActiveModel::Serializers

Upvotes: 0

Views: 30

Answers (1)

Max
Max

Reputation: 15955

If you define an as_json method that returns a hash, ActiveRecord will take care of the serialization for you. E.g.

class Product < ActiveRecord::Base
  def as_json options = {}
    {
      product: <product value>,
      pricing: <pricing value>,
      # ... etc.
    }
  end
end

Now you can do:

> Product.first.to_json
  => "{\"product\":<product_value> ... }"

You can even render these as json from the controllers via:

render json: @model

Upvotes: 1

Related Questions