Composability of structs generated by Ecto Schemas

Hello Everyone!

Apologies if this question has been posted before, but I couldn’t find anything.

Let’s say I have two physical tables with 11 fields each. They share the same nine fields, but differ in the 10th and 11th fields. I have a separate schema for each table.

Is there any way to specify a “master” struct, such that the master struct contains the nine common fields, as well as a field for a struct that contains the table specific fields? Is there a way to populate such a struct via Ecto? I’d guess not, but I wanted to make sure.


You could just put the shared fields in a macro and call it in the other schemas to populate them perhaps?

Honestly I’d split the parts into different tables myself though. :slight_smile:


Thanks for the reply!

Yes, I could do that and that would solve part of my problem regarding code reuse.

Ideally, I would like to have a master struct so that I can match against it in function args and have a guarantee that the argument would indeed have all 9 shared fields. I suppose my question is transformable to: How can I ensure that a given struct passed as an argument has a given set of fields?

EDIT: I think compostability is the general solution, but it does not seem to work with structs populated via Ecto schemas :frowning:

Thanks again!

1 Like

Other option would be to put those 9 fields they share on an embedded schema and use embeds_one/3 with cast_embed/3. This way you can reuse their definition and validations, but still don’t need to create a table just for them. Of course in this case you would have to change the table structure, if that’s not an option nevermind. :grinning: lets you drop the result information into any structure of your choice, independent of a schema.


I might be off-topic, but can you maybe create three schemas, one “master” with the 9 shared fields, and two children with their specific fields?