I have a league model and the league has_many Teams. I only want a user to be able to create one team per league. I'm finding this validation to be tricky. Here is what I'm currently trying.
def changeset(%Team{} = team, attrs \\ %{}) do
team
|> cast(attrs, [:name, :league_id, :user_id])
|> validate_required([:name, :league_id, :user_id])
|> one_team_per_user_for_leagues
end
defp one_team_per_user_for_leagues(team) do
if team.changes == %{} do
team
else
league = Repo.get!(League, team.changes[:league_id]) |> Repo.preload(:teams)
Enum.map(league.teams, fn(team) -> team = team end) |> Enum.any?
end
end
But I'm getting this error: no function clause matching in Ecto.Repo.Schema.insert/4
Full stacktrace:
Request: POST /teams
** (exit) an exception was raised:
** (FunctionClauseError) no function clause matching in Ecto.Repo.Schema.insert/4
(ecto) lib/ecto/repo/schema.ex:157: Ecto.Repo.Schema.insert(Statcasters.Repo, Ecto.Adapters.Postgres, false, [])
(statcasters) lib/statcasters_web/controllers/team_controller.ex:21: StatcastersWeb.TeamController.create/2
(statcasters) lib/statcasters_web/controllers/team_controller.ex:1: StatcastersWeb.TeamController.action/2
(statcasters) lib/statcasters_web/controllers/team_controller.ex:1: StatcastersWeb.TeamController.phoenix_controller_pipeline/2
(statcasters) lib/statcasters_web/endpoint.ex:1: StatcastersWeb.Endpoint.instrument/4
(phoenix) lib/phoenix/router.ex:278: Phoenix.Router.__call__/1
(statcasters) lib/statcasters_web/endpoint.ex:1: StatcastersWeb.Endpoint.plug_builder_call/2
(statcasters) lib/plug/debugger.ex:99: StatcastersWeb.Endpoint."call (overridable 3)"/2
(statcasters) lib/statcasters_web/endpoint.ex:1: StatcastersWeb.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /Users/cameronbass/Desktop/Play/statcasters/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
This also doesn't feel like the "Elixir Way" Can anyone help me untangle this?