简体   繁体   中英

Rails query gives different ordering during testing

My query works properly on the rails console and the web server where it returns a DESC order but fails during testing where it returns ASC order.

Below is the simplified model code.

class Room < ApplicationRecord
 has_many :room_members
 has_many :members, through: :room_members, source: :user

 def self.hot_rooms
  query = "SELECT r.*, rm,count
           FROM rooms r
           LEFT JOIN (SELECT room_id, count(room_id), max(id) as id
                      FROM room_members
                      GROUP BY room_id) rm
           ON r.id = rm.room_id
           WHERE r.is_started = true
           ORDER BY rm.count DESC, rm.id DESC
           LIMIT 12"
  self.find_by_sql(query)
 end
end
  • Fixtures test data
  • No errors except ordering
  • PostgreSQL 9.6.1
  • Rails 5.0.1
  • Ruby 2.3.1p112

The problem is rm.count DESC .
The result of Room.recent_rooms is DESC on console and web server but surprisingly ASC when testing.

I fixed. The problem was caused by 'nil' count.(There was no nil on console) psql count out nil instead of 0. And It assume nil as a big number I think. So I modified the code, and I solved the problem.

  1. wm.count > coalesce(wm.count,0) as count
  2. rm.count DESC > count DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM