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

IncorrectDependentOption should consider touch and counter_cache association options #130

Open
fatkodima opened this issue Feb 22, 2023 · 0 comments

Comments

@fatkodima
Copy link
Contributor

Example:

class User
  has_many :projects
  has_many :commits
end

class Project
  belongs_to :user
  has_many :commits, dependent: :delete_all
end

class Commit
  belongs_to :project
  belongs_to :user, counter_cache: true # same applies for when `touch: true`
end

If model has an association defined with touch or/and counter_cache, IncorrectDependentOption decides that it is safe to delete this model (if all other conditions are met).

Updating counter cache is implemented without any callbacks - https://github.com/rails/rails/blob/c4b050984a0a9433e2ac79409e69154f55cfb247/activerecord/lib/active_record/counter_cache.rb#L186-L199, and touching via update, touch and sometimes destroy (if no counter cache) callbacks - https://github.com/rails/rails/blob/c4b050984a0a9433e2ac79409e69154f55cfb247/activerecord/lib/active_record/associations/builder/belongs_to.rb#L78-L100

So, 1) counter caches will gets stale or 2) parent records won't be touched (possibly some cache will became stale).
For the example from the top: if we call project.destroy, then relevant commits will be DELETEd, and the relevant user won't be touched.

So, I suggest if the model has such associations with counter_cache or touch options defined, it is not safe to delete them.

If you are ok with such changes, I will open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant