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.
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:
Models are simple:
class Sku < ApplicationRecord
belongs_to :product
end
class Product < ApplicationRecord
has_many :skus
end
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.
I copy the above SQL, which generated by ORM, and run it in SQL tool (TablePlus), it return 5 rows.
http://localhost:3000/?page=5
It shows Displaying sku 5 - 4 of 4 in total
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.