Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear out target when no new records #45244

Merged

Commits on Jun 6, 2022

  1. Clear out target when no new records

    When counting records for a has_many association, we were previously
    getting in an out-of-sync state if there were records in memory that
    were persisted to the database, but did not count for the scoped query.
    
    This impacts associations with a scope like so:
    ```
    class Coupon < ActiveRecord::Base
      has_many :coupon_redemptions, -> { where(expired: false) }
    end
    ```
    
    Using the example above, let's say we hold a loaded `coupon_redemption`
    record in memory and it switches from `expired: true` to `expired:
    false`. Assuming that change is persisted to the database, we should
    respect it when working with that record in memory.
    
    When we first call `coupon.coupon_redemptions.size`, we get the
    appropriate response: 0. But when we call it again, we get 1 record.
    That's because in the second call, the record has already been loaded
    from the DB and we get into the out-of-sync state.
    
    The fix was to ensure the has_many association target list is empty when
    counting records in that scenario.
    
    Co-authored-by: Daniel Colson <composerinteralia@github.com>
    luanzeba and composerinteralia committed Jun 6, 2022
    Configuration menu
    Copy the full SHA
    db0e0c0 View commit details
    Browse the repository at this point in the history