如何将 has_and_belongs_to_many 个关系对象放在一起
How to get has_and_belongs_to_many relation objects together
我有如下所示的 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
}
],
},
有没有好的rails方法来做到这一点?
我可以像上面那样手动创建对象,但是如果有一个更简单的查询就更好了。
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
它会return一个像这样的数组:
[
{
"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"
},
]
}
]
我有如下所示的 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
}
],
},
有没有好的rails方法来做到这一点?
我可以像上面那样手动创建对象,但是如果有一个更简单的查询就更好了。
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
它会return一个像这样的数组:
[
{
"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"
},
]
}
]