marcin

marcin

Hi! :wave:

I’d like to ask how you implement a super common functionality, for which I do not see any easy way in Ecto.Changeset

Lets say I have a Todo which belongs to a TodoList.

I get my auto-generated changeset() using phx.gen.schema which looks roughly like this:

  def changeset(todo, attrs) do

    todo
    |> cast(attrs, [:title, :details, :done])
    |> validate_required([:title])
  end

Now I would like to also be able to pass the association into this function, so in my context API todos.ex I can do:

def move_todo_to_list(todo, todo_list) do
   update_todo(todo, %{todo_list: todo_list})
end

obviouly in changeset() I cannot cast() the todo_list.
I need to call either put_assoc(), or change() - however, the association is not always given, I can also just have this usage from controller

def create_todo(params) do
  %Todo{} 
  |> Todo.changeset(params)
  |> Repo.insert()
end

where params would contain todo_list_id

I do not want to do any conditional handling in my changeset, nor defp some multiclause helpers:

  def changeset(todo, attrs) do
    chset = todo
    |> cast(attrs, [:title, :details, :done])
    
    # OMG verbose!!!!
    chset = if attrs[:todo_list] do
      put_assoc(chset, attrs[:todo_list], todo_list)
    else
      chset
    end

    chset
    |> validate_required([:title])
  end

(note, some custom validations might use the association to figure out if an attribute is valid or not, so validate goes last).

I used to do kinda elegant:

  def changeset(todo, attrs) do
    assocs = Map.take(attrs, [:todo_list])

    todo
    |> cast(attrs, [:title, :details, :done])
    |> change(assocs)
    |> validate_required([:title])
  end

But this will not work if attrs are sometimes keyed by strings (data from user), and sometimes by atoms (programmer controlled params from some module), and then when I add :todo_list key, i might end up with “cannot mix strings and atom keys” error from cast().

I bet this has to be solved somehow elegantly, this is such a common use case – but cannot come up with anything based on Ecto standard functions other then writing some custom helpers…

Showing Posts 1 to 4

LostKobrakai

LostKobrakai

How about the following?

def move_todo_to_list(todo, todo_list) do
   update_todo(todo, %{todo_list_id: todo_list.id})
end
marcin

marcin OP

That does not cover a useful situation when the assoc is not yet in the db (let’s say I created a new todo with its own list, and will let Repo.insert both)

LostKobrakai

LostKobrakai

Tbh at a certain point it’s just not worth it trying to treat every possible scenario as “one and the same”. Ecto has useful APIs for all the usecases you mentioned. It’s however not going to be one API covering all of them at the same time.

dimitarvp

dimitarvp

I agree with @LostKobrakai here but if you really insist, you can just make a function with multiple heads, one of which covers a nil primary / foreign key.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

AstonJ
We’ve spoken about AI-related job losses for a while now, and while Elixir may be a little more protected than some languages so there’s ...
New
GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews