Ruby on rails 按“所属对象”关系分组列表,包括所有“所属对象”属性
我有以下型号:Ruby on rails 按“所属对象”关系分组列表,包括所有“所属对象”属性,ruby-on-rails,ruby,group-by,nested,Ruby On Rails,Ruby,Group By,Nested,我有以下型号: class User < ActiveRecord::Base belongs_to :room end class Room < ActiveRecord::Base has_many :users validates :name, presence: true validates :location, presence: true end 这给了我以下散列: { 1=>[array of users
class User < ActiveRecord::Base
belongs_to :room
end
class Room < ActiveRecord::Base
has_many :users
validates :name, presence: true
validates :location, presence: true
end
这给了我以下散列:
{
1=>[array of users belonging to room with id 1],
2=>[array of users belonging to room with id 2]
}
我想要一系列房间,包括他们的用户,如下所示:
users.group_by(&:room_id)
[
{
id: 1,
name: room1,
location: location1,
users: [array of users belonging to room with id 1],
},
{
id: 2,
name: room2,
location: location2,
users: [array of users belonging to room with id 2]
}
]
尝试
Room.joins(:users)。选择(“rooms.name,rooms.location”).group('rooms.id')
这将为每个房间提供所有用户。我希望按文件室排序的用户列表将根据用户的属性(姓名、年龄、性别)进行筛选。基本上,我只需要按房间过滤的用户列表。