1

I have two rails controller actions:

  def show
    @project = Project.find(params[:id])
    render json: @project,
      :only => [:id, :compilation_id],
      :methods => :track_name,
      :include => {
        :user => { :only => [:id, :email] }
      }
  end

  def list_users
    render json: User.select(:id, :email)
  end

I would like to render them both in one response. What is the best way to go about doing this? I tried using the to_json method as described here but I read that that method is deprecated and I also noticed that it escapes the content which seems to be unnecessary. Any help is appreciated.

Community
  • 1
  • 1
laertiades
  • 1,992
  • 2
  • 19
  • 26

2 Answers2

1

For the cases where you need json structures complicated enough for to_json to look readable, I recommend to use active_model_serializers gem.

You can then define two serializer classes like this:

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :compilation_id

  has_many :users
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email
end

And then in your controller:

class ProjectsController < ApplicationController
  def show
    @project = Project.find(params[:id])
    render json: @project, serializer: ProjectSerializer, status: 200
  end
end

As a bonus track, you can even cache the response!

dgilperez
  • 10,716
  • 8
  • 68
  • 96
0

The solution, of course, was pretty simple:

project = Project.select(:id, :compilation_id, :user_id, :genre_id, :ordering).find(params[:id])
render json: { :project => project,
               :users => User.select(:id, :email),
               :genres => Genre.select(:id, :name),
               :track_name => project.track_name
             }
laertiades
  • 1,992
  • 2
  • 19
  • 26