使用respond_with包含多个关联 [英] Including multiple associations using respond_with

查看:83
本文介绍了使用respond_with包含多个关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 user post role 模型在ruby 1.9.3上运行的Rails 3应用程序.一个用户有很多帖子和角色.

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.

我的routes.rb文件如下:

My routes.rb file look like this:

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

在列出所有用户时,我想在json响应中包括相关的帖子角色.我找到了一种仅包含其中一个一个的方法,如下所示:

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

哪个给我以下json响应

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?

推荐答案

u可以将'include'用作

u can use 'include' as

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

引用 http://apidock.com/rails/ActiveRecord/Serialization/to_json 了解更多信息

这篇关于使用respond_with包含多个关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆