Search code examples
sqlruby-on-railsactiverecordhas-and-belongs-to-many

How to get has_and_belongs_to_many relation objects together


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.


Solution

  • 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":"[email protected]",
      "groups":[
         {
           "id":1,
           "name":"Yo"
         },
         {
           "id":2,
           "name":"Bro"
         },
      ]
    },
    
    {
      "id":2,
      "email":"[email protected]",
      "groups":[
         {
           "id":1,
           "name":"Arya"
         },
         {
           "id":2,
           "name":"Stark"
         },
      ]
    }
    ]