mathieuprog

mathieuprog

Hello :waving_hand:

I published a library that brings support for polymorphic/dynamic embeds in Ecto.

Ecto’s embeds_one macro requires a specific schema module to be specified. This library removes this restriction by dynamically determining which schema to use, based on data to be stored (from a form or API) and retrieved (from the data source).

Example use case:

Say you have a Reminder schema. A reminder has a set date and text, but also specific fields whether it is an email reminder or sms reminder. Instead of adding and mixing all the email- and sms-related fields together in the Reminder schema, where one set of fields or the other are null values, you can add a polymorphic embed, only containing the relevant sms or email fields. The polymorphic embed also supports its own changeset validations.

See example code and usage in Readme file :backhand_index_pointing_down:

https://github.com/mathieuprog/polymorphic_embed

Inspired by ecto_poly library.

Showing Posts 1 to 10

thomas.fortes

thomas.fortes

Awesome, I’ve been working exactly with this problem this past week, my solution was built with an Ecto custom type, it works perfectly, but there’s a lot of boilerplate…

From the docs it seems like it will be almost a plug and play with just some minor adjustments, will open a branch and try it :slight_smile:

Edit: Yeah, looking at the source of the lib it does what I was doing manually with a custom type, it took zero modifications in the code aside of changing the field type in the schema and configuring the lib, so far all the tests passed.

mathieuprog

mathieuprog OP

I imagine this is a pretty common need, and that many codebases would either have a schema with sets of null values, or end up having their own custom Ecto type implementations.

This library indeed provides a custom Ecto Type that determines the right embed schema to use, based on params to cast. Nice thing is, you can tell PolymorphicEmbed that the presence of specific params identifies a certain schema – no need for a “type” field in the params:)

In addition to the advantages that a library offers (get rid of boilerplate code in the app, reusable code across projects, bugfixes, …), it comes with some nice features:

  • As mentioned, detect which types to use for the data being cast-ed, based on fields present in the data (no need for a type field in the data)
  • Run changeset validations when a changeset/2 function is present (when absent, the library will introspect the fields to cast)
  • Support for nested polymorphic embeds
  • Support for nested embeds_one/embeds_many embeds
  • Display form inputs for polymorphic embeds in Phoenix templates

Added those features in the Readme file.

nwjlyons

nwjlyons

This looks really cool. I wonder if I could recreate Wagtail’s StreamField with this. Going to investigate…

mathieuprog

mathieuprog OP

polymorphic_embed is now using ParameterizedType! :clap:

Polymorphic embeds are now specified as parameters on the field:

schema "reminders" do
  field :channel, PolymorphicEmbed,
    types: [
      sms: MyApp.Channel.SMS,
      email: MyApp.Channel.Email
    ]

No more intermediary module for options, code injection and macros.

Note also that for those using it, an (unrelated) bugfix requires now casting params for polymorphic embeds through cast_polymorphic_embed/2 instead of cast/4.

See example in readme.

mathieuprog

mathieuprog OP

Support for lists of polymorphic embeds has been added! Thanks to the great contribution of @jmnsf.

Code has also been drastically simplified and improved thanks to brilliant contributions from @maennchen.

The :on_replace option has been added and must be set to :update for single polymorphic embeds and :delete for lists of polymorphic embeds. These are the only supported modes when replacing records. We force to specify the option as omitting this option for embeds_one/embeds_many defaults its value to :raise.

mathieuprog

mathieuprog OP

Support for ecto_sqlite3 has been added in version 1.7.0!

Other features added:

  • :with option allowing to specify a custom changeset;
  • :required option to specify whether the embed is required or not;
  • traverse_errors/2 function to include polymorphic embeds’ errors.
belaustegui

belaustegui

Just wanted to jump in and say thanks for this awesome library @mathieuprog

We have been using it for the last few months at my day job and it has been an absolute pleasure. Works well and reliably and the documentation is top-notch.

mathieuprog

mathieuprog OP

  • Support for LiveView forms has been added thanks to the quality contribution of Mathias!

  • Support for primary keys has been added

The latter may introduce breaking changes, therefore Polymoprhic Embed version has been bumped to 2.0.0

Migration from 1.x to 2.x is easy:

  • Make sure that every existing polymorphic embedded_schema contains the setting @primary_key false
mathieuprog

mathieuprog OP

Version 3.0.0 has been released!

We now encourage the use of polymorphic_embeds_one/2 and polymorphic_embeds_many/2 macros to define your polymorphic embeds.

If you’re curious as to why: a field containing a polymorphic list of embeds defaulted to nil before version 3. To follow embeds_many/3 we should default to []. This can only be done by forcing the :default option of the field/3 to [] (ie we can’t configure this in the Type). I added the new macros in order to set these kind of defaults setting up the field for the polymorphic embeds.

Thanks to Alexandre @Matsa59 for his contribution which led to this update!

mathieuprog

mathieuprog OP

A tricky bug has been fixed where atoms were not persisted in the compilation files. The atoms specifying the types were converted into strings in the Ecto Type’s init/1 function at compile-time, and so as we only worked with the strings afterwards, the atoms were not persisted:
https://github.com/mathieuprog/polymorphic_embed/issues/59

Fixed in 3.0.3 thanks to the support of @LostKobrakai on Slack and the contribution of Alessio ! :clap:

Where Next? Top

Trending in Announcing Top

bluzky
You may know https://ui.shadcn.com/, a UI component library for React. I really love it’s design style and components. I’ve built some co...
387 15136 120
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
restlessronin
The repo is at GitHub - cyberchitta/openai_ex: Community maintained Elixir library for OpenAI API · GitHub. Docs are at OpenaiEx User Gu...
152 11030 135
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
shahryarjb
The Chelekom project is a library of Phoenix and LiveView components generated via Mix tasks to fit developer needs seamlessly. One of i...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
woylie
Phoenix components for pagination, sortable tables and filter forms with Flop and (optionally) Ecto. pagination cursor pagination sorta...
New

Other Trending Topics Top

mudasobwa
I am seeing a lot of aplications of Argumentum ad Vericundiam in software discussions. They do link some piece of writing and point us to...
New
bartblast
Hey folks, I just published a post about Hologram’s funding and where the project goes next - the short version: Curiosum as Main Spons...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
sorenone
Today we’re releasing Oban for Python. Not an Oban client in Python. Not a pythonx wrapper embedded in Elixir. Nope, it’s a fully operati...
New
lawik
I was thinking since Goatmire Elixir turned out pretty good I should maybe do another one. 30th of Sep - 2nd of Oct this year./ The firs...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews