diff --git a/README.md b/README.md index f5a9301..21425bd 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/). -_487 TILs and counting..._ +_488 TILs and counting..._ --- @@ -106,6 +106,7 @@ _487 TILs and counting..._ - [Run ExUnit Tests In A Deterministic Order](elixir/run-exunit-tests-in-a-deterministic-order.md) - [String Interpolation With Just About Anything](elixir/string-interpolation-with-just-about-anything.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) ### Git diff --git a/elixir/virtual-fields-with-ecto-schemas.md b/elixir/virtual-fields-with-ecto-schemas.md new file mode 100644 index 0000000..37e7a96 --- /dev/null +++ b/elixir/virtual-fields-with-ecto-schemas.md @@ -0,0 +1,30 @@ +# Virtual Fields With Ecto Schemas + +If you'd like to include a particular key-value pair in an Ecto changeset, +it needs to be included as a field in the schema. In the case of something +akin to a password field, you want to be able to perform validations against +it, but the password itself does not have a column in the database. In other +words, you want to use the password in memory as part of the validation +process but not save it to the database. To accomplish this, you need to +specify that it is a `virtual` field. + +```elixir +schema "users" do + field :username, :string + field :password_digest, :string + field :password, :string, virtual: true +end +``` + +With that schema, you can then validate the `:password` and transform it +into the corresponding `:password_digest` field. + +```elixir +def registration_changeset(model, params) do + model + |> changeset(params) # do other standard validations + |> cast(params, [:password]) # include :password in the changeset + |> validate_length(:password, min: 8) # validations + |> put_pass_hash() # transform into :password_digest +end +```