我有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
}
],
},
这样做有很好的方法吗?
我可以像上面那样手动创建对象,但是查询更简单会很好。
答案 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"
},
]
}
]