geared_pagination icon indicating copy to clipboard operation
geared_pagination copied to clipboard

Fix records_count when using group by

Open smridge opened this issue 2 years ago • 0 comments

Changes

  • Fixed records_count to handle hashes (typically returned with group). As it stands, only ActiveRecord_Relation are handled. This fix ensures an integer is always returned.
  • Changed count to size to avoid any misleadings / documentation collisions.
  • Fixes https://github.com/basecamp/geared_pagination/issues/8

Detail

Currently, when using select to load custom attributes that are grouped on the Model, the count breaks when evaluating @page.last?. Specifically, this breaks on while residual > 0 with the error of no implicit conversion of Integer into Hash.

After looking at the method-i-count docs

If count is used with Relation#group for multiple columns, it returns a Hash whose keys are an array containing the individual values of each column and the value of each key would be the count.

This explains the quirk.

Example usage:

# in model
scope :with_custom_selections, lambda {
  joins(:bars).select(
    <<~SQL.squish
      foos.*,
      count(bars.id) as bars_count
    SQL
  ).group(:id)
}

# in controller
@foos = set_page_and_extract_portion_from(Foo.with_custom_selections)

# in view
<% if @page.last? %>
...

smridge avatar Dec 03 '22 02:12 smridge