Pablo Palacios
Pablo Palacios

Reputation: 2957

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?

Ex.

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
  else
    render json: { error_description: 'no complex found' },status: :bad_request
end

Upvotes: 3

Views: 3405

Answers (2)

Elias Perez
Elias Perez

Reputation: 413

An easy way to do this is to build a hash with your objects

complex = Complex.find(params[:id])
search_params = {complex_id: complex._id}
fields = Field.where(search_params)

render json: { complex: complex, fields: fields, search_params: search_params }, status: :ok

Another way would be to user a view such as some_view.json.erb where you render the objects as you are expecting it in your angular view. Also you can use can use ActiveModelSerializers, read on https://github.com/rails-api/active_model_serializers

Ideally what you will want to do is encapsulate this response into its object and make a single call in your controller that returns you the results

Without going into too much details something like this

results = MyComplexFieldsObj.response(params[:id])
render son: results, status: :ok

Upvotes: 4

Jim Van Fleet
Jim Van Fleet

Reputation: 1118

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.

Upvotes: 1

Related Questions