0

I have HABTM associated tables like below.

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
end

How do I get User(s) with associated Groups together(nested), like below

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

Is there a nice rails way of doing this?

I can manually create object like above but it would be nice to have a simpler query.

Bigair
  • 1,452
  • 3
  • 15
  • 42

1 Answers1

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

It'll return an array like:

[
{
  "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"
     },
  ]
}
]
Emu
  • 5,763
  • 3
  • 31
  • 51