ruby-on-railsjsonrespond-with

Including multiple associations using respond_with


I have a rails 3 app running on ruby v. 1.9.3 with a user, post and role model. A user has many posts as well as roles.

My routes.rb file look like this:

namespace :api, defaults: {format: 'json'} do
  resources :users do
    resources :posts
    resources :roles
  end
end

I want to include the associated posts and roles in the json response when listing all the users. I have found a way to include only one of them, like this:

#users_controller.rb
def index
  @users = User.all        
  respond_with @users, :include => :posts
end

Which gives me the following json response

[{
"created_at":"2013-06-17T13:10:59Z",
"id":1,
"username":"foo"
"posts":[ a list of all the users posts ]
}]

But what I want is a result looking like this:

[{
"created_at":"2013-06-17T13:10:59Z",
"id":1,
"username":"foo"
"posts":[ a list of all the users posts ]
"roles":[ a list of all the users roles ]
}]

How should I modify my code to achieve this?


Solution

  • u can use 'include' as

    User.all.to_json(:include => [:posts, :roles])
    

    refer http://apidock.com/rails/ActiveRecord/Serialization/to_json for more info