I am trying to get all rooms and order them by number of users in each room.
Each user who enters the room, stored in table roulettes, but I need rows which were added only 90 seconds ago.
This query return room ordered by number of users, but doesn't return room if the number of coresponding roulettes is zero, but I want to get all rooms.
scope :with_users_in, -> { select("rooms.id, rooms.title, rooms.creation_time, rooms.room_life, count(roulettes.id) AS listens_count").
joins("LEFT OUTER JOIN roulettes ON roulettes.section_id = rooms.id").
group("rooms.id").
order("listens_count DESC").
where("roulettes.time > (? - 90)", Time.now.to_i)
}
How can I modify my query?
For example, if rewrite my scope like this:
scope :with_users_in, -> { select("rooms.id, rooms.title, rooms.creation_time, rooms.room_life, count(roulettes.id) AS listens_count").
joins("LEFT OUTER JOIN roulettes ON roulettes.section_id = rooms.id").
where("roulettes.time > (? - 900000) OR roulettes.time IS NULL", Time.now.to_i).
group("rooms.id").
order("listens_count DESC")
}
I get this json:
[{"id":1,"title":"fdf","creation_time":1442706728,"room_life":20000300,"url":"http://localhost:3000/rooms/1.json","listens_count":2}]
But for origin query I get []
. Because last entering in room was much before than 90 seconds. And I want it to return the same thing, but instead of listens_count:2
get listens_count:0
The generated code
Room Load (0.3ms) SELECT rooms.id, rooms.title, rooms.creation_time,
rooms.room_life, count(roulettes.id) AS listens_count FROM "rooms" LEFT
OUTER JOIN roulettes ON roulettes.section_id = rooms.id WHERE
(roulettes.time > (1442941851 -90) OR roulettes.time IS NULL) GROUP BY
rooms.id ORDER BY listens_count DESC LIMIT 20 OFFSET 0