Thanks to visit codestin.com
Credit goes to github.com

Skip to content

total_count gives wrong result after a calling map on an empty AR::Relation instance #845

@denislins

Description

@denislins

Hey guys,

I think I've found a very weird bug. It appears that calling #map on a activerecord relation instance breaks #total_count, but only when the relation is empty. I've successfully reproduced it using both PostgreSQL and SQLite in their latest versions.

You can get a better vision of the issue in the code below:

def get_coupons(request, options)
  coupons = coupons(request)

  CouponsResponse.new(
    coupons: parsed_coupons(coupons), total: coupons.total_count,
    results_per_page: 10)
end

private

def coupons(request)
  Coupon.valid_at(request.valid_from).page(request.page).per(10)
end

def parsed_coupons(coupons)
  coupons.map do |coupon|
    ...
  end
end

The expected result is:

{ coupons: [...], total: 2, results_per_page: 10 }

While the actual result is:

{ coupons: [...], total: 10, results_per_page: 10 }

I tried searching the issues but didn't find anything related. Please forgive me if this is a known issue, or if it's my fault and therefore not an issue at all.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions