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 building front-end systems with anything from vanilla JS to React. Infosec student and active learner. Subscribe to the blog

www ·

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.