I am using rails 4. I have a two models- "Company" & "Employees". Company has_many employees. I want to fetch the company and get all the employees in its nested dictionary in API like this,
In company controller I tried
In company model
scope :for, ->(id) do
Employee.joins(:company).where(:company_id => id).to_a
and getting this output
But I need company's attributes also. Please help.
Best How To :
This is something that you need to handle in the views with a proper response builder.
acts_as_api suggested by @rob works, Rails starting from v4.0 has built in support for building and sending rich JSON responses using a typical builder style DSL. It is called
jbuilder - https://github.com/rails/jbuilder
Just like you have
.html.erb views, you define
.json.jbuilder views in the same directory and you are all set to create any type of JSON response.
Particular advantage with
acts_as_api is the support for partials (similar to erb templates) and also the fact that the response logic will be in a
view as opposed to a
P.S: I used
acts_as_api until Rails added support for
jbuilder views in v4.0