Convert Ecto Changeset to Struct

ecto

#1

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?


#2

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?


#3

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.


#4

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


#5

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.