How to update multi records?

a tuple list data like this

tuples = [{"user_1", 87}, {"user_2", 93}]

Now I want to update these data to table like this:

update user set score = 87 where user_name = user_1;
update user set score = 93 where user_name = user_2;

Could someone please help me? Thanks.

I write this code

def test_update8() do
	tuples = [{"user_1", 2}, {"user_2", 3}]
	Ecto.Multi.new()
	|> do_something(tuples)
	|> Repo.transaction()

end

defp do_something(multi, tuples) do
	Enum.reduce(tuples, multi, fn tuple, multi ->
		multi.update_all(String.to_atom(elem(tuple, 0)), from(v in __MODULE__, where: v.user_name == ^elem(tuple, 0)), [inc: [score: 0 - elem(tuple, 1)]])
	end)
end

but i get this error message

** (ArgumentError) you attempted to apply a function on %Ecto.Multi{operations: [], names: MapSet.new([])}. Modules (the first argument of apply) must always be an atom

Try with multi.update as a start. You would update all records N amount of times (N == size of the list).

This was close:

The biggest problem was that in elixir you’re not dealing with objects and not calling methods on them. Instead you call functions, which are organized in modules. So it should be Ecto.Multi.update_all in the reduce, which takes the existing multi as a parameter.

def test_update8() do
	tuples = [{"user_1", 2}, {"user_2", 3}]
	
	Ecto.Multi.new()
	|> do_something(tuples)
	|> Repo.transaction()

end

defp do_something(multi, tuples) do
	Enum.reduce(tuples, multi, fn {user, value}, multi ->
		Ecto.Multi.update_all(
			multi, 
			{:update_user, user}, 
			from v in __MODULE__, where: v.user_name == ^user, [set: [score: value]],
			[]
		)
	end)
end
1 Like

Thanks very much!