hawkyre
Updating structs with Ecto changesets and put_assoc
Hey there, this is my first post in here! I’m “just” in need of a little help with changesets and associations.
I have a changeset I built that works wonders to create and validate structs. However, now that I want to also add functionality to update structs this one’s not gonna do it since I’m using put_assoc and passing in the params to my helper function:
def changeset(%Course{} = struct, params \\ %{}) do
struct
|> cast(params, [:title, :description])
|> put_assoc(:scopes, parse_scopes(params), required: true)
|> validate_required([:title, :description])
end
defp parse_scopes(params) do
(params["scopes"] || [])
|> Enum.map(fn name ->
Repo.get_by(Scope, name: name)
end)
end
If I wanted to just update the title, I would just pass in the title through params and the existing course through struct, but that would mean the scopes would be reset to none since put_assoc destroys any association.
What is the best way to approach this problem?
Also, I’ve got another problem with this and it is that if the user passes in an invalid scope this will throw an error and I have no idea how to catch that in a clean way. I may open a new question for this later but I’d appreciate it if someone had some insight on this too.
Thanks a lot!
Edit: fixed a word
First Post!
trowl3r
Hey,
I don’t know, if that is, what you are looking for, but maybe try to use build_assoc since this don’t overwrite the association.







