diff --git a/README.md b/README.md index 335364f..8843268 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_499 TILs and counting..._ +_500 TILs and counting..._ --- @@ -110,6 +110,7 @@ _499 TILs and counting..._ - [Run ExUnit Tests In A Deterministic Order](elixir/run-exunit-tests-in-a-deterministic-order.md) - [Same Functions Should Be Grouped Together](elixir/same-functions-should-be-grouped-together.md) - [String Interpolation With Just About Anything](elixir/string-interpolation-with-just-about-anything.md) +- [Unique Indexes With Ecto](elixir/unique-indexes-with-ecto.md) - [Updating Values In A Map](elixir/updating-values-in-a-map.md) - [Virtual Fields With Ecto Schemas](elixir/virtual-fields-with-ecto-schemas.md) - [Word Lists For Atoms](elixir/word-lists-for-atoms.md) diff --git a/elixir/unique-indexes-with-ecto.md b/elixir/unique-indexes-with-ecto.md new file mode 100644 index 0000000..15baf4b --- /dev/null +++ b/elixir/unique-indexes-with-ecto.md @@ -0,0 +1,21 @@ +# Unique Indexes With Ecto + +You can create a unique index in a migration for one or more columns using +the [`unique_index/3`] function. + +For example, if you are creating a join table for `followers` and want to +ensure that duplicate _follower_ entries are prevented, you may want to +include a unique index like so: + +```elixir +create table(:followers) do + add :followed_user, references(:users), null: false + add :following_user, references(:users), null: false +end + +create unique_index(:followers, [:followed_user, :following_user]) +``` + +Keep in mind that `unique_index/3` is a shorthand for +[`index/3`](https://hexdocs.pm/ecto/Ecto.Migration.html#index/3) when you +set `unique: true`.