Correct / optimal usage of Ecto.Changeset for non-models

Hi there,

I am creating my first dummy/test application with Phoenix. My question is however related to Ecto.Changeset
I have my models, but if just want to use a changeset to validate a user input, that is not related to any model, for example, see the code below. I have search term and I want to validate it, but use the value afterwards. I dont have access to apply_changes/1 outside of my model, and I am hesitant to import it. So I put it into my function here, but now I loose the nice thing about changesets which is composability, so that I could easily stick another changeset function after this one etc. Am I just overthinking it, or am I doing something fundamentally wrong?

kind regards

def search_changeset(%{"q" => term} = params) do
    changeset =
      cast( {%{q: ""}, %{q: :string}} , params, [:q])
      |> validate_length(:q, min: 3)
    IO.inspect changeset
    case changeset.valid? do
      true ->
        {:ok, apply_changes(changeset)}
      _ ->
        {:error, changeset}

Use an embedded_schema as described here:

There’s an example Registration module in the blog posts that is similar to what you need.

1 Like