Updated: Don't name columns like counter_cache columns in Rails pre v4.2.4

Posted . Visible to the public. Auto-destruct in 48 days

Added a link to the commit resolving the issue and included the affected rails versions.

Changes

  • +## < Rails v4.2.4
  • +
  • ActiveRecord has a feature called [counter caching](http://hiteshrawal.blogspot.de/2011/12/rails-counter-cache.html) where the containing record in a `has_many` relationship caches the number of its children. E.g. when you have `House has_many :rooms`, Rails can cache the number of rooms in `House#rooms_count`.
  • Mind that when a model has a column that looks to Rails like a counter-cache column, Rails will apply counter-cache logic to your model, **even if you're not using counter caches**.
  • E.g. you have a house with 12 rooms, but `house.rooms_count` is 0 (for whatever reason). Now `house.rooms` will always be empty because Rails thinks that there is no point in querying the database.
  • -A solution is to use another naming convention (like `total_rooms`).
  • +A solution is to use another naming convention (like `total_rooms`).
  • +
  • +## >= Rails v4.2.4
  • +
  • +`#has_cached_counter?` enforces that the `counter_cache` option must be given on either the owner or inverse since this [commit](https://github.com/rails/rails/commit/e0cb21f5f767606ad3ecf2db33855d27aa9f083d#diff-13a4fc1eb1d70c2e2e5948fbb258d80e1b1aa3468c2061b261bb4a69bdbbc89fL82-L85), whereas it only looked at the presence of the attribute before.
  • +
Felix Eschey
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2024-07-01 07:56)