我有一个在 ruby v.1.9.3 上运行的 Rails 3 应用程序,具有用户、帖子和角色模型。一个用户拥有多个帖子和角色。
我的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 ]
}]
我应该如何修改我的代码来实现这一目标?
最佳答案
你可以使用“包含”作为
User.all.to_json(:include => [:posts, :roles])
引用http://apidock.com/rails/ActiveRecord/Serialization/to_json了解更多信息
关于ruby-on-rails - 使用 respond_with 包含多个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213052/