Define reference to an Active Record that has a custom table defined
Here is a #Rails pro tip I discovered while trying to write a migration for defining a belong_to association to a model that had a custom table instead of relying on the Rails convention:
![belongs_to association](https://cdn.scribbles.page/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBaUYwIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--5acb1a5350036caa242339bfd771c8ad41958b7b/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdDRG9MWm05eWJXRjBTU0lJY0c1bkJqb0dSVlE2RkhKbGMybDZaVjkwYjE5c2FXMXBkRnNIYVFJQUNHa0NBQVk2Q25OaGRtVnlld2M2Q25OMGNtbHdWRG9NY1hWaGJHbDBlV2xrIiwiZXhwIjpudWxsLCJwdXIiOiJ2YXJpYXRpb24ifX0=--768aeab7fb7843d85fe5b2b4ba237e06e6ef604f/1.png)
The solution I found was to use an option called to_table
defined on
the foreign_key
attribute of TableDefinition#references
![How to use `to_table`](https://cdn.scribbles.page/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBaUowIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--5de3faf67930d594dd662b5372a77dc7241e435b/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdDRG9MWm05eWJXRjBTU0lJY0c1bkJqb0dSVlE2RkhKbGMybDZaVjkwYjE5c2FXMXBkRnNIYVFJQUNHa0NBQVk2Q25OaGRtVnlld2M2Q25OMGNtbHdWRG9NY1hWaGJHbDBlV2xrIiwiZXhwIjpudWxsLCJwdXIiOiJ2YXJpYXRpb24ifX0=--768aeab7fb7843d85fe5b2b4ba237e06e6ef604f/2.png)
Documentation about this can be found at:Â
- Rails Guides - Active Record Migrations\#foreign_keys
- Rails Guides - Association Basics\#self-joins
- Rails API - SchemaStatements\#add_reference