【问题标题】:How to get has_and_belongs_to_many relation objects together如何将 has_and_belongs_to_many 关系对象放在一起
【发布时间】:2016-06-17 05:29:49
【问题描述】:

我有如下的 HABTM 关联表。

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
end

如何将用户与关联的组放在一起(嵌套),如下所示

{
    id: 8,
    name: "John",
    groups: [
      {
        id: 17,
        name: "Alpha Group",
        user_id: 8
      },
      {
        id: 18,
        name: "Bravo Group",
        user_id: 8
      }
    ],
},

有没有一种很好的 Rails 方法可以做到这一点?

我可以像上面那样手动创建对象,但如果有一个更简单的查询会很好。

【问题讨论】:

  • 你在渲染json对象吗?
  • get User(s) with associated Groups together(nested) 是什么意思?你想在你的视图中渲染它吗?
  • 您能否发布您的控制器代码,通过该代码生成上述响应?
  • 是的,我需要返回 json。在控制器中,渲染状态:200,json:

标签: sql ruby-on-rails activerecord has-and-belongs-to-many


【解决方案1】:
def index
  @group = Group.find(params[:id])
  respond_to do |format|
    format.html
    format.json { @group.users.map do |user|
                 user.to_json(:include => :groups)
               end
             }
  end
end

它会返回一个像这样的数组:

[
{
  "id":1,
  "email":"admin@example.com",
  "groups":[
     {
       "id":1,
       "name":"Yo"
     },
     {
       "id":2,
       "name":"Bro"
     },
  ]
},

{
  "id":2,
  "email":"valar@example.com",
  "groups":[
     {
       "id":1,
       "name":"Arya"
     },
     {
       "id":2,
       "name":"Stark"
     },
  ]
}
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多