Skip to content
Mike Bradford edited this page May 25, 2012 · 1 revision

Rails gives us several options for building and rendering a resource in JSON. Let's evaluate some of them.

Using ActiveRecord.as_json

Pros

  1. Easy. Just let the controller renderer handle it.

Cons

  1. Larger data sizes because all attributes are included.
  2. No customization.

Override ActiveRecord.as_json in the model

Pros

  1. Allows for customization of data.
  2. Can reduce response sizes as you can include only the attributes you need.
  3. Still easy.

Cons

  1. Puts view code in the model layer.
  2. Not always easy to combine JSON from different models.
  3. Testing of JSON rendering divided between model and controller tests.

Using a builder

Pros

  1. Allows for complete customization.
  2. Use of controller and view helpers.
  3. Keeps response testing in controller tests.
  4. Still easy. Just a small learning curve.

Cons

  1. No out-of-the-box support in Rails. Must use a separate gem.

Conclusion

I believe that using a builder is the most advantageous approach. For this example, we'll use the rabl gem. I like it over jbuilder because I prefer its DSL for reusing JSON output and it still gives us the possibility to add builders of other formats.

Clone this wiki locally