2016-06-17 2 views
0

私は以下のようなHABTM関連テーブルを持っています。has_and_belongs_to_manyリレーションオブジェクトを一緒に取得する方法

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

以下のように、一緒に(ネスト)の関連グループとユーザー(複数可)を得るのですか?

上記のように手動でオブジェクトを作成することはできますが、より簡単なクエリを使用するとよいでしょう。

+0

あなたは 'json'オブジェクトをレンダリングしていますか? – Emu

+0

'関連付けられたグループと一緒に(ネストされた)ユーザーを取得する 'とはどういう意味ですか?これをあなたの視点で表現しようとしていますか? – oreoluwa

+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":"[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" 
    }, 
    ] 
} 
] 
関連する問題