JSON Strategies - 47primes/recipes_api GitHub Wiki
Rails gives us several options for building and rendering a resource in JSON. Let's evaluate some of them.
Using ActiveRecord.as_json
Pros
- Easy. Just let the controller renderer handle it.
Cons
- Larger data sizes because all attributes are included.
- No customization.
Override ActiveRecord.as_json in the model
Pros
- Allows for customization of data.
- Can reduce response sizes as you can include only the attributes you need.
- Still easy.
Cons
- Puts view code in the model layer.
- Not always easy to combine JSON from different models.
- Testing of JSON rendering divided between model and controller tests.
Using a builder
Pros
- Allows for complete customization.
- Use of controller and view helpers.
- Keeps response testing in controller tests.
- Still easy. Just a small learning curve.
Cons
- 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.