Running before_insert in Phoenix Elixir

If you have a generated Phoenix model and you want to run a function before insert, something like setting a UUID of a user you should run code like this.

In your <modelname>.ex in your initial model code (begins with defmodule Reviewmymp.User do)

before_insert :put_uuid

A few lines under in the same file you can put your function such as:

def put_uuid(changeset) do
  Ecto.Changeset.put_change(changeset, :uuid, Ecto.UUID.generate())
end

About Nick

Melbourne based web developer that loves Laravel, Ruby on Rails, Phoenix/Elixir, Writing, Travel, Jiu-Jitsu and Starcraft.

www ·

Leave a Reply

Your email address will not be published.