2013-06-20 95 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 ] 
}] 

我該如何修改我的代碼來達到這個目的?

回答