2013-06-20 55 views
2

多个关联我有一个轨道上的红宝石V上运行的应用程序3。1.9.3与用户作用模型。用户有很多帖子和角色。包括使用respond_with

我的routes.rb文件是这样的:

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

我想包括相关职位和列出所有用户当JSON响应角色。我已经找到一种方法只包括其中之一,像这样:

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

这给了我下面的JSON响应

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

但我想是这样看的结果:

[{ 
"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 ] 
}] 

我该如何修改我的代码来达到这个目的?

回答