MVZ
MVZ

Reputation: 2250

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?

Upvotes: 4

Views: 1470

Answers (2)

James Lim
James Lim

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

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.

Upvotes: 7

Richard Cook
Richard Cook

Reputation: 33089

Another approach is to use jbuilder which allows you much finer-grained control over how your JSON is generated:

  • Add the jbuilder gem to your app
  • Use JBuilder.encode from your controllers to generate JSON
  • Alternatively, create .json.jbuilder templates in your views directories

Upvotes: 0

Related Questions