choey choey - 1 month ago 11
JSON Question

How to resolve relations in a query for JSON

I have 2 tables, Jedis and Padawans, with a many to many relationship through a third table, Apprenticeship. their app/models rb files define their relations like this:

Jedi:

class Jedi < ActiveRecord::Base
attr_accessible :name
has_many :apprenticeships
has_many :padawans, :through => :apprenticeships
end


Padawan:

class Padawan < ActiveRecord::Base
attr_accessible :name
has_many :apprenticeships
has_many :jedis, :through => :apprenticeships
end


Apprenticeship:

class Apprenticeship < ActiveRecord::Base
attr_accessible :jedi_id, :padawan_id
belongs_to :jedi
belongs_to :padawan
end


When I query like this:

@apprenticeships = Apprenticeship.where(jedi_id: 1)


And return the results to the front-end as JSON:

respond_to do |format|
format.json { render json: @apprenticeships }
end


The JS ajax call that initiated the request receives an array of objects, each representing an apprenticeship record. Each object looks like this (stringified):

"{"id":1,"created_at":"2016-10-25T04:42:24.020Z","updated_at":"2016-10-25T04:42:24.020Z","jedi_id":1,"padawan_id":1,"apprenticeship_status":null}"


At this point in the process, I would prefer the apprenticeship records to be this instead (with ids resolved to objects):

"{"id":1,"created_at":"2016-10-25T04:42:24.020Z","updated_at":"2016-10-25T04:42:24.020Z","apprenticeship_status":null,"jedi":{"id":1,"name":"Yoda"},"padawan":{"id":1,"name":"Luke Skywalker"}}"


What is the correct, cleanest method of accomplishing this using only Ruby - so JS can receive the proper array of objects to work with?

Thanks for your help.

Answer

When you transform the object to_json, try using:

@apprenticeships.to_json(include: [:jedi, :padawan])