Blog

Serving Custom JSON Responses With ActiveModel::Serializers

These days, there are so many different choices when it comes to serving data from an API. In many cases, you just want to bring something to market as fast as you can. For those times, I still reach for Ruby on Rails.

When building an API in Rails, you need a good solution for structuring your JSON. ActiveModel::Serializers (AMS) is a sensible choice. It's powerful alternative to jbuilder, rabl, and other Ruby templating solutions. It's easy to get started with, but when you want to serve data that quite doesn't match up with the way ActiveRecord (AR) structures things, it can be hard to figure out how to get it to do what you want.

In this post, we'll take a look at how to extend AMS to serve up custom data in the context of a Rails-based chat app.

Read More

Keeping your JSON response lean in Rails

Many folks are guilty of just spitting back everything on a ActiveRecord model in JSON with render :JSON in their actions. I've certainly been guilty of this. Problem is this pretty much sucks because you're sending down a whole lot more data than you probably need to. The end user suffers especially on a mobile device and that's just not cool. This can get really bad when you need to have multiple associated models represented in your JSON response. So how do you keep your JSON as lean as possible?

No one wants to add a bunch of options in your asJSON methods inside of each action. Makes your controller look like a total mess! To get around that I highly recommend using asJSON in your models and not using to_JSON at all on your ActiveRecord models when your creating a data result. Lets look at some code on how to best handle this.

Read More