Convert Ecto Changeset to Struct

So I want to use Ecto to validate some form input data, but then turn that data back into a typed struct to pass into a function which is typechecking arguments. Is there a way to do this?

4 Likes

Why not typecheck directly the changeset, I would say that’s the right thing to do actually. Is there something more about your case? What do you mean with typecheck?

1 Like

When you want to turn changeset into struct (e.g. without inserting to the DB), you can use Ecto.Changeset.apply_changes/1 but be careful: it’s gonna return a struct regardless if the changes was valid or not, so you’ll probably want to validate it explicitly first.

14 Likes

Thank you! That’s what I was looking for (don’t worry, validating the changeset first :slight_smile: ).

2 Likes

Update: As of Ecto 2.2.0 there’s even an Ecto.Changeset.apply_action/2 that additionally checks whether the changeset is valid or not.

8 Likes

Update: As of Ecto 3.3.0 there’s even an Ecto.Changeet.apply_action!/2 :smiley:

6 Likes

finally :slight_smile:

1 Like