Where should code from Join Schema Example be placed?

In the Join Schema Example for Ecto.Schema many_to_many (listed below for convenience), where do the changeset and case statement go? I’m assuming it’d be in user_organization_controller.ex but I’m having trouble getting it to work.

  def create(conn, %{"user_organization" => user_organization_params}) do
    changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id})

    case Repo.insert(changeset) do
      {:ok, assoc} -> # Assoc was created!
      {:error, changeset} -> # Handle the error
    end
  end

Code example from the Ecto hexdocs:

defmodule UserOrganization do
  use Ecto.Schema

  @primary_key false
  schema "users_organizations" do
    belongs_to :user, User
    belongs_to :organization, Organization
    timestamps # Added bonus, a join schema will also allow you to set timestamps
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> Ecto.Changeset.cast(params, [:user_id, :organization_id])
    |> Ecto.Changeset.validate_required([:user_id, :organization_id])
    # Maybe do some counter caching here!
  end
end

defmodule User do
  use Ecto.Schema

  schema "users" do
    many_to_many :organizations, Organization, join_through: UserOrganization
  end
end

defmodule Organization do
  use Ecto.Schema

  schema "organizations" do
    many_to_many :users, User, join_through: UserOrganization
  end
end

# Then to create the association, pass in the ID's of an existing
# User and Organization to UserOrganization.changeset
changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id})

case Repo.insert(changeset) do
  {:ok, assoc} -> # Assoc was created!
  {:error, changeset} -> # Handle the error
end
1 Like

I’m having trouble getting it to work.

What errors are you getting?
Is there a route to the UserOrganisationController in the Router module?

1 Like

Yes, the route exists.

Error: undefined function id/0

Complete message:

$ mix phx.server
Compiling 1 file (.ex)

== Compilation error in file lib/x_web/controllers/admin/user_organisation_controller.ex ==
** (CompileError) lib/x_web/controllers/admin/user_organisation_controller.ex:28: undefined function id/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:121: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1
```
1 Like

Based on the error message and the code snippet you provided, looks like you are not assigning anything to the variable id when calling UserOrganization.changeset()

Perhaps you need to read id from user_organization_params ?

3 Likes

Thanks! This was it.