[openstreetmap/openstreetmap-website] Add `inverse_of` to various model associations (Issue #3471)
Andy Allan
notifications at github.com
Wed Feb 23 15:46:16 UTC 2022
Normally Rails can autodetect bi-directional associations. This has two advantages:
* Saves memory. If you do e.g. `issue.reports.first.issue` you get the same object back, without having to load `issue` fresh from the database (or duplicate it from the query cache).
* Makes validations easier. If you have a new `issue`, with a new `report`, then the validation will pass even though `report.issue_id` is currently blank - rails knows it will be filled in later.
However, [Rails can't autodetect this bi-directional association whenever a `foreign_key` is specified](https://guides.rubyonrails.org/association_basics.html#bi-directional-associations). The solution is to specify the `inverse_of` on certain relationships where the autodetection fails. Unfortunately for us, we have a lot of explicitly specified `foreign_key` options!
Rubocop can find these cases for us, without making us specify them on everything. So we should enable [Rails/InverseOf](https://github.com/openstreetmap/openstreetmap-website/blob/172a71e3f242f74a6eb1f7bb45fb4d5f3ddff5e7/.rubocop.yml#L58-L59) ([cop docs](https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsinverseof)) and add the inverse relationships.
--
Reply to this email directly or view it on GitHub:
https://github.com/openstreetmap/openstreetmap-website/issues/3471
You are receiving this because you are subscribed to this thread.
Message ID: <openstreetmap/openstreetmap-website/issues/3471 at github.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openstreetmap.org/pipermail/rails-dev/attachments/20220223/cebd8638/attachment.htm>
More information about the rails-dev
mailing list