marcin

marcin

Conditionally associate in a simple changeset() function

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…

First Post!

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

Most Liked

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.

Last Post!

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.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36820 110
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement