Skip to content

Allow resetting singular associations #46165

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

Merged
merged 1 commit into from
Nov 23, 2022
Merged

Allow resetting singular associations #46165

merged 1 commit into from
Nov 23, 2022

Conversation

georgeclaghorn
Copy link
Contributor

@georgeclaghorn georgeclaghorn commented Sep 30, 2022

has_one :author and belongs_to :author each define a reload_author method on the owning model. reload_author clears the cached author associate-object and eagerly fetches a new one from the database.

In some cases, you know the cached associate is stale but not whether it will be needed again. If it isn’t, the database query from calling reload_* is wasted.

Consider the following models:

class Account < ApplicationRecord
  has_many :trials
  has_one :active_trial, -> { active }, class_name: "Trial"
end

class Trial < ApplicationRecord
  belongs_to :account
  
  scope :active, -> { where active: true }

  def deactivate
    update! active: false
    # 📍
  end
end

At the 📍 in Trial#deactivate, we know we’ve potentially made account’s active_trial association stale. We don’t know if account will need to reference its active_trial again. It would be useful to be able to evict the cached active_trial, if any, and defer the database query until the next access.

For collection associations, ActiveRecord::Associations::CollectionProxy provides a #reset method in addition to #reload. There’s not an equivalent way to reset a singular association, though. This PR adds one.

@rafaelfranca rafaelfranca merged commit e32e092 into rails:main Nov 23, 2022
@georgeclaghorn georgeclaghorn deleted the singular-association-reset branch November 23, 2022 20:26
tk0miya added a commit to tk0miya/rbs_activerecord that referenced this pull request Nov 12, 2024
Since v7.0, `#{association}_changed?` and
`#{association}_previously_changed?` methods were generated to the
belongs_to associations.

In addition, since v7.1, `reset_#{association}` was also generated
to both has_one and belongs_to associations.

refs:

* rails/rails#42751
* rails/rails#46165
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants