Pablo Palacios Pablo Palacios - 9 months ago 36
Ruby Question

How to render two json objects as response on a rails controller

I need some help I have a controller with an action that queries two models.
Now I need to send both of them as json in order to be used on my angular views.

In the example bellow how should I send the "complex" and its "fields" in one json response?


def complexes_and_fields
complex = Complex.find(params[:id])
search_params = {complex_id: complex._id}
fields = Field.where(search_params)
if !complex.nil?
render json: ???.to_json, status: :ok
render json: { error_description: 'no complex found' },status: :bad_request


This is an extremely common requirement in Rails applications. This need is rarely restricted to a single model, or a single location. As a result, a variety of gems exist to provide this kind of functionality (in many cases, without altering the signature of your render lines substantially).

This post offers a good listing. Personally, I've had a good experience with active_model_serializers and an acceptable experience with grape-entity. It's reasonable to review their documentation and decide which is best for you.