cannot invoke remote function inside match : Foreach loop

12,092

There are a few issues here. The = operator is the match operator, it is not assignment. To explain the error, syntax-wise, this looks like function invocation on the left hand side of a match, which is not allowed.

But this is besides the point of your actual goal. If you want a set of user models that are updated with the new bcrypt information, you need to use a map function:

users = Enum.map(users, fn %User{id: id}=user ->
          %User{user| token: Comeonin.Bcrypt.hashpwsalt("#{id}")}
        end)

You have to remember that everything in Elixir is immutable.

Share:
12,092
naveen
Author by

naveen

Updated on July 18, 2022

Comments

  • naveen
    naveen almost 2 years

    I'm trying to set some property of User model inside a for-each loop, But I keep getting following error

    cannot invoke remote function x.token/0 inside match (elixir) src/elixir_fn.erl:9: anonymous fn/3 in :elixir_fn.translate/3 (stdlib) lists.erl:1353: :lists.mapfoldl/3 (elixir) src/elixir_fn.erl:14: :elixir_fn.translate/3

    Method:

    Enum.each(users, fn(user) ->
      user.token = Comeonin.Bcrypt.hashpwsalt(to_string(user.id))
    end)