Tuesday, November 11, 2014

Rails Active model serializers

When to use active model serializer ?

    When you have your app running on both browser and mobile app, and if you have a backend rails server then active model serialiser is a perfect gem for serving api’s.

There are other gems like rabl but I personally prefer this gem because this is extremely easy to use and it has lot of + points.


Step 1.

    Add gem into your Gemfile

    gem ‘active_model_serializers'


Step 2.

    Create a serializer file by running

    rails g serializer user


    which will create  app/serializers/user_serializer.rb



Step 3.

    In serializer, you can add attributes, associations, custom methods.

    attributes :id, :name, :followers, :timestamp


So here id and name are user fields. Followers is an association in user. timestamp is a custom method.

You can define that method like this.

    def timestamp
        object.created_at.strftime(“%B %d %Y”)
    end       

Step 4.

    In your controller, you probably would have added

        respond_to :json, :html 
    and in action

        respond_with @user

When you visit /users/1.json
   
{

    "user": {
        "id": 1,
        "email": "foodoo@example.com",
        "name": "Foo doo",
        "microposts": [
            {
                "id": 1,
                "content": "This is a micropost",
                "user_id": 1,
                "created_at": "2014-11-11T16:11:08.500Z",
                "updated_at": "2014-11-11T16:11:08.500Z"
            }
        ],
        "followers": [ ]
    }

}