Skip to content

IncorrectDependentOption should consider touch and counter_cache association options #130

@fatkodima

Description

@fatkodima

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    false negativeAn error wasn't reported when it should

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions