【问题标题】:Rails - Include an association in the result of a queryRails - 在查询结果中包含关联
【发布时间】:2015-05-13 08:41:42
【问题描述】:

我想在结果中获取每个用户的所有地址。 做这样的事情:

User.all.includes(:addresses)(用户有多个地址)

并且想得到类似的东西:

[[id:1, name:"user1", 地址:[[id:1, street:"第五大道", 城市:“纽约”],[id:2,街道:“大道”,城市:“巴黎”]]],[id:2, 名称:“user2”,地址:[[id:3,街道:“跳街”,城市:“la”]]], ...]

因为它是一个 json 响应。

【问题讨论】:

  • 那你的问题是什么?
  • 我想得到像我的例子一样格式化的结果。

标签: jquery ruby-on-rails ruby json


【解决方案1】:

试试这样的:

users = User.includes(:addresses).all
users.as_json(include: :addresses)

这应该会返回预期的结果。

希望有帮助!

【讨论】:

  • 这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
相关资源
最近更新 更多