mrkaspa
mrkaspa

Reputation: 75

How should I implement callbacks in phoenix with ecto?

If callbacks will be deprecated https://github.com/elixir-lang/ecto/issues/1114 and Multi isn't implemented yet, how should I do this?

Upvotes: 0

Views: 1775

Answers (2)

Daniel Perez
Daniel Perez

Reputation: 6903

It depends what callback you are trying to replace. As Jason mentioned, for the before_insert, just call a function in your changeset instead.

If you are trying to replace before_update, after_update or after_delete, create a function that does all your stuff wrapped in a transaction.

I cannot think of a case that cannot be handled this way, but if you do, update your question with a specific use case.

Upvotes: 0

Jason Harrelson
Jason Harrelson

Reputation: 2693

You can just call the "callback" function in the changeset. So for instance, if you have a changeset for creating a product that needs an identifier GUID generated, you may have implemented this with callbacks.

defmodule Product do
  before_insert :generate_identifier

  defp generate_identifier(changeset) do
    ...
  end
end

Now you can just call it in your changeset function, which is more explicit.

defmodule Product do
  def create_changeset(model, attrs) do
    model
    |> cast(attrs, @required_fields, @optional_fields)
    |> generate_identifier
    |> validate_present(:name)
  end

  defp generate_identifier(changeset) do
    ...
  end
end

You can pipe into validators and other types of callbacks.

Upvotes: 4

Related Questions