diff --git a/README.md b/README.md index 9df00e0..781d86f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1068 TILs and counting..._ +_1069 TILs and counting..._ --- @@ -649,6 +649,7 @@ _1068 TILs and counting..._ - [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md) - [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md) - [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md) +- [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md) - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) - [Custom Validation Message](rails/custom-validation-message.md) - [Customize Paths And Helpers For Devise Routes](rails/customize-paths-and-helpers-for-devise-routes.md) diff --git a/rails/create-a-custom-named-references-column.md b/rails/create-a-custom-named-references-column.md new file mode 100644 index 0000000..1667598 --- /dev/null +++ b/rails/create-a-custom-named-references-column.md @@ -0,0 +1,47 @@ +# Create A Custom Named References Column + +The `t.references` and `add_reference` methods both create a foreign key column +name based on the target table. + +For instance, + +```ruby +add_reference :guests, :user, foreign_key: true, index: true, null: false +``` + +would create a `user_id` column on the `guests` table. + +At times, you'll need to customize the name of the foreign key column. The +Rails migration DSL supports this with the `foreign_key` option. + +Here is an example that shows the syntax for both a new table and an existing +table. + +```ruby +class AddInvitedByColumnToUser < ActiveRecord::Migration[6.1] + def change + create_table :guests, id: :uuid do |t| + t.string :email, null: false + t.timestamps + + t.references :invited_by, + type: :uuid, + index: true, + null: false, + foreign_key: { to_table: :users } + end + + add_reference :guests, :signed_up_as, + type: :uuid, + index: true, + null: false, + foreign_key: { to_table: :users } + end +end +``` + +The `t.references` call creates a foreign key column to the `users` table named +`invited_by`. The `add_reference` call adds a `signed_up_as` foreign key column +to `guests` that points to users. + +[source](https://stackoverflow.com/a/42056089/535590)