Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, including relationships in json render

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?

like image 630
MVZ Avatar asked Mar 22 '23 19:03

MVZ


1 Answers

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

Side Note

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.

like image 173
James Lim Avatar answered Mar 25 '23 19:03

James Lim