choey choey - 1 year ago 68
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:


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


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


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

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 }

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


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 Source

When you transform the object to_json, try using:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download