I have a small Phoenix app that handles user registration.
Each user belongs to a Sector, and each Sector has many users. The schemas are defined as:
schema "users" do
belongs_to :sector, MyApp.Sector
end
schema "sectors" do
has_many :users, MyApp.User
end
In my Phoenix controller, I do some validations and load all the sectors, building a User association, like this:
sector =
Repo.get!(Sector, user_params["sector_id"])
|> Repo.preload(:users)
user = Ecto.build_assoc(sector, :users)
changeset = User.changeset(user, user_params)
I really don’t know if that’s the most idiomatic way, but it worked. Users are inserted belonging to the specified Sector.
The problem is when I try to update it. In traditional SQL, this means changing the sector_id
from the User. I have tried the following:
user = Repo.get!(User, id) |> Repo.preload(:sector)
changeset = User.changeset(user, user_params)
changeset =
Ecto.Changeset.put_assoc(changeset, :sector, Repo.get!(params["sector_id"]))
or even:
user = Repo.get!(User, id) |> Repo.preload(:sector)
user = %{ user | sector: Repo.get!(Sector, params["sector_id"])
changeset = User.changeset(user, user_params)
But the sector that came from params
is ignored in the update.
What am I doing wrong?
Thanks!