Reputation: 2250
I have the following code which returns a json with some data that includes @admin_user.companies:
@admin_user = User.find_by_email(email)
render :json=>{:status=>{:code=>200,:token=>@admin_user.authentication_token,
:user=> @admin_user,
:companies => @admin_user.companies }}
Each company also have many "locations". How do I include all the locations for every single company in @admin_user.companies in the json?
Upvotes: 4
Views: 1470
Reputation: 13054
The conventional way is to use
render json: @admin_user.companies, include: :locations
(Please refer to #as_json
for more options.)
You don't need to include the status code in your JSON, since it's already in the HTTP headers. Thus, the following might get you close to what you need.
render :json => @admin_user,
:include => {
:companies => { :include => :locations },
},
:methods => :authentication_token
This is just an example. You will have to configure :include
and :methods
to get exactly what you want. For even more fine-grained control, look into JBuilder or RABL.
Upvotes: 7
Reputation: 33089
Another approach is to use jbuilder which allows you much finer-grained control over how your JSON is generated:
jbuilder
gem to your appJBuilder.encode
from your controllers to generate JSON.json.jbuilder
templates in your views
directoriesUpvotes: 0