Updating a child in a one to many relationship

Hello, I have user-country relationship and getting the following error when tryng to update the country for a user :

** (FunctionClauseError) no function clause matching in Ecto.Changeset.add_constraint/7 (ecto) lib/ecto/changeset.ex:2742: Ecto.Changeset.add_constraint(#Ecto.Changeset<action: nil, changes: %{countries_id: 1}, errors: [], data: #Turnos.Users.User<>, valid?: true>, :foreign_key, "users_1_fkey", :exact, 1, "does not exist", :foreign)

My schema for user is :

schema "users" do
   .
   .
   belongs_to(:countries, App.Countries.Country, foreign_key: :countries_id)

   timestamps()
end

and the countries schema is:

schema "countries" do
    .
    .

    timestamps()

    has_many(:users, App.Users.User, foreign_key: :countries_id)
  end

The user update changeset look like this:

def update_changeset(usuario, attrs) do
    usuario
    |> cast(attrs, @lista_cast)
    |> validate_required(@lista_validate_require)
    |> foreign_key_constraint(attrs["countries_id"]) 
    |> unique_email()
  end

I put :countries_id in @lista_cast .

In the foreign_key_constraints you are passing the value of the fk, it expects the field name as an atom , it should probably be :


def update_changeset(usuario, attrs) do
    usuario
    |> cast(attrs, @lista_cast)
    |> validate_required(@lista_validate_require)
    |> foreign_key_constraint(:countries_id) 
    |> unique_email()
  end

1 Like

Thank you. That worked.