Save the result from the loop to a list of variables

I want to insert a group of similar objects and get the ID of each one in one fell swoop. I am trying this:

q1 = "question1"
q2 = "question2"
q3 = "question3"
q4 = "question4"

Enum.each([q1, q2, q3, q4], &(Repo.insert!(......)))

# working with q1 and id of q1
# .......


# working with q2 and id of q2
# .......

# and so on

      

Is there a way, perhaps, to create a second list of variables where I would store the result model being returned Repo.insert

? If not, how do I access the "id" of each inserted model: q1-q4? Or should I instead insert them one by one, and would it be easier and easier?

+3


source to share


2 answers


You are looking for Enum.map/2

:

ids = [q1, q2, q3, q4]
|> Enum.map(&Repo.insert!(......))
|> Enum.map(&Map.get(&1, :id))

      




You can also do it step by step:

structs = Enum.map([q1, q2, q3, q4], &Repo.insert!(......))
ids     = Enum.map(ids, &Map.get(&1, :id))

      

+1


source


There are many ways to do this. One is to create a separate list of ids and then iterate over both lists with Enum.zip/2

:

q1 = "question1"
q2 = "question2"
q3 = "question3"
q4 = "question4"

ids = Enum.map([q1, q2, q3, q4], &(Repo.insert!(......)))

for {q, id} <- Enum.zip([q1, q2, q3, q4], ids) do
  IO.inspect {q, id}
end

      

Another is to return a question / id pair from Enum.map

(I'm using for

here for clearer code, but you can also use Enum.map/2

):



pairs = for q <- [q1, q2, q3, q4] do
  {q, Repo.insert!(...)}
end

      

Then repeat the same way:

for {q, id} <- pairs do
  IO.inspect {q, id}
end

      

+1


source







All Articles