ledowong / sql_count

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue

count value is incorrect, when using joins and group together, and group by multi-table ID. The following example, expected return 5, but Rails count return 4. Cross checked in SQL database, it return 5 rows.

Steps to reproduce

Setup

Checkout this sample project, then run the following in console:

bundle
rails db:migrate
rails db:seed

It create Products and Skus table, and create sample record in DB. You should have something like this in database: products skus

Models are simple:

class Sku < ApplicationRecord
  belongs_to :product
end

class Product < ApplicationRecord
  has_many :skus
end

Reproduce in rails console

Run Sku.joins(:product).group("skus.id, products.id").size in rails console, it generate a COUNT SQL, and return a hash, which I guess it means 4. (kaminari return 4 too. kaminari/kaminari#968) But if I load it into memory first, and call size again, it return 5, which is expected. console

I copy the above SQL, which generated by ORM, and run it in SQL tool (TablePlus), it return 5 rows. SQL

Reproduce in kaminari

http://localhost:3000/?page=5 It shows Displaying sku 5 - 4 of 4 in total kaminari

Sample explanation

This example JOIN and GROUP BY both table IDs, I know this usage doesn't make sense. The actual use case is much more complex JOIN, and GROUP BY more columns (including both table IDs). I try to simplifies it, to just a simple JOIN and GROUP BY. Although this sample's GROUP BY look odd, but it is simple and correct Rails syntax.

About


Languages

Language:Ruby 79.6%Language:HTML 15.3%Language:JavaScript 3.2%Language:CSS 1.9%