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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With