如何将has_and_belongs_to_many关系对象放在一起

时间:2016-06-17 05:29:50

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

我有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
      }
    ],
},

这样做有很好的方法吗?

我可以像上面那样手动创建对象,但是查询更简单会很好。

1 个答案:

答案 0 :(得分: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"
     },
  ]
}
]