Dynamic embedded schema based on type

I have a json/map field in database which can actually holds 3 kinds of objects based on type field define in table

so structure is like this

field(:type, :string) => user/player/admin
field(:object, :map) => embedded schema needed here. and it can be any of the three schemas ie user/admin/player

So is this possible I can have the flexibility of mysql and beauty/support of Ecto embeds.

Check out this library:

1 Like

Seems nice. But how to change to specific embedded schema based on field type(please check my structure above) in the actual table/schema. This library can deduct embeds type based on the given fields which can lead to issues. what if FE sends data in wrong format and these params werent even present. we should be able to tell them errors just based on type(which will be always present)

The library knows which embed to use based on a type field ("__type__" or :__type__ param); this is documented in the readme file. It can also deduct the type based on the presence of data, but that is optional.

This :__type__ should be inside json object field?

That’s one way to achieve it. If the frontend calls the same service for handling different kind of data, then it makes sense that it is included by the frontend. Otherwise you may also pick the right embed on the server.

Note also that it is hard or probably impossible to have the structure that you have shown, i.e. have the type stored only in a separate field. That’s because when using a custom Ecto Type for the field (storing the dynamic embed), you do not have access to the other fields of the schema. So for example, if you want to load the data from the DB, in order to load the right embed struct you really need to have that type field living with your data.