mathieuprog / polymorphic_embed

Polymorphic embeds in Ecto
Apache License 2.0
341 stars 63 forks source link

Allows customizing polymorphic changeset #36

Closed jmnsf closed 3 years ago

jmnsf commented 3 years ago

I need to run a different changeset function given some conditions. This allows passing a :with option to cast_polymorphic_embed/3 with an atom for the changeset function to use.

I picked the same name as cast_embed/3, but the expected type is different since there's no way to pass a polymorphic function ref as well.

ckampfe commented 3 years ago

I need to run a different changeset function given some conditions. This allows passing a :with option to cast_polymorphic_embed/3 with an atom for the changeset function to use.

I picked the same name as cast_embed/3, but the expected type is different since there's no way to pass a polymorphic function ref as well.

Glad to see someone else raise this issue and make this PR, as it's something we need as well. Basically, we want to be able to choose the embedded changeset based on the state of the parent schema. It seems like this is not possible in the library currently but this change appears to solve it!

mathieuprog commented 3 years ago

Thank you for the PR @jmnsf ! I've added this feature in v1.4.0

However I did a bit differently:

changeset
|> cast_polymorphic_embed(:channel,
  with: [
    sms: {SMS, :custom_changeset, ["foo", "bar"]},
    email: &Email.custom_changeset/2
  ]
)
mathieuprog commented 3 years ago

By the way, could you briefly explain me your use case? I'm curious to know the reason to use custom changesets.

jmnsf commented 3 years ago

Cool 👌🏼

I've different validation requirements for an embedded schema depending on whether it's a draft or a final version, so I use different changesets for each case.