0

I've a model and 2 controllers as follow :

class MyModel < ActiveRecord::Base
    def serializable_hash(options={})
        super(only: [:id, :foo])
    end
end

module V1
    class MyController < ApplicationController
        def show
            render json: {my_model: @my_model}
        end
    end
end

module V2
    class MyController < ApplicationController
        def show
            render json: {my_model: @my_model}
        end
    end
end

I want to be able to return a different json depending on the controller :

class MyModel < ActiveRecord::Base
    def serializable_hash(options={})
        # If V1
        super(only: [:id, :foo])
        # ElsIf V2
        super(only: [:id, :bar])
        # End
    end
end

I would like to find a generic solution, so I don't have to send the version manually in parameters.

Jérôme Boé
  • 2,752
  • 4
  • 21
  • 32

1 Answers1

0

It would be better to decouple the serialization from your model i.e. don't put the serialization code in the model. You have a few options: Using a json builder in your views directory, or using ActiveModelSerializers. Both approaches will make it easy to version your serialization code:

JSON builders:

# app/views/v1/my_controller/my_model.json.builder

json.my_model do
  json.id @my_model.id
  json.foo @my_model.foo
end

With the above set up you can imagine easily adding a v2 directory with a different serializer.

In your controller you don't even need to specify a render call since rails will notice you have a builder in your controller's view directory. More info about jbuilder in this Railscast

ActiveModelSerializers:

Same goes with serializers, they are just files in app/serializers. You can put your files in app/serializers/v1/my_model_serializer.rb.

The concept with these two approaches is to use Rails modular paths to version your files. A controller in app/controller/v1 will load files from other directories with the same v1: app/serializers/v1.

Here's the railscast for active model serializers. And the asciicast.

Also, here's a gem that helps with api versioning: https://github.com/EDMC/api-versions I use it and find it nice to work with.

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55
  • Thx diego. I may have a problem with ActiveModelSerializer though : http://stackoverflow.com/questions/26159813/versioning-activemodelserializer – Jérôme Boé Oct 02 '14 at 11:30