Error: "no function clause matching in Keyword.get/3" when calling Ecto.changset

I’m running into the following errors, going through the Ecto getting started docs.

Calling

person = %Friends.Person{}
changeset = Friends.Person.changeset(person, %{})

Produces

** (FunctionClauseError) no function clause matching in Keyword.get/3     
    
    The following arguments were given to Keyword.get/3:
    
        # 1
        :last_name
    
        # 2
        :trim
    
        # 3
        true
    
    Attempted function clauses (showing 1 out of 1):
    
        def get(keywords, key, default) when is_list(keywords) and is_atom(key)
    
    (elixir 1.13.3) lib/keyword.ex:352: Keyword.get/3
    (ecto 3.8.4) lib/ecto/changeset.ex:1796: Ecto.Changeset.validate_required/3

person.ex


defmodule Friends.Person do
  use Ecto.Schema

  schema "people" do
    field(:first_name, :string)
    field(:last_name, :string)
    field(:age, :integer)
  end

  def changeset(person, params \\ %{}) do
    person
    |> Ecto.Changeset.cast(params, [:first_name, :last_name, :age])
    |> Ecto.Changeset.validate_required(:first_name, :last_name)
  end
end

migration

defmodule Friends.Repo.Migrations.CreatePeople do
  use Ecto.Migration

  def change do
    create table(:people) do
      add :first_name, :string
      add :last_name, :string
      add :age, :integer
    end

  end
end

Hey @2FO welcome! The issue is that this line here should be:

|> Ecto.Changeset.validate_required([:first_name, :last_name])

Basically you’re passing in the atom :last_name into the argument that would be the options value. To pass in multiple fields that should be required you should use a list.

2 Likes