3
votes

I have an Ecto model that I want to be stored in the database with a custom binary_id generated from an elixir function. Is this possible?

My id function looks like this:

def gen_id
    String.upcase to_string Enum.take_random('abcdefghjkmnpqrstuvwxyz123456789', 8)
end

My schema looks like this:

schema "orders" do
    belongs_to :type, Invoicer.Customer
    @primary_key {:id, :binary_id, autogenerate: true}
    field :order_details, :string

    timestamps()
end
1

1 Answers

4
votes

You should implement your own type following the Ecto.Type behaviour.

Within that type, you can add an autogenerate/0 function, which is your gen_id function, to generate the id for you.

To see a completed example of something like this, you can take a look at Ecto.UUID which has everything you are asking for here.