Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto: Custom binary_id

Tags:

elixir

ecto

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
like image 558
hyde Avatar asked Sep 05 '26 09:09

hyde


1 Answers

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.

like image 145
Justin Wood Avatar answered Sep 08 '26 18:09

Justin Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!