如何用elixir种子数据?

时间:2016-11-30 14:28:07

标签: elixir

我试图将数据投放到数据库中,但它无法正常工作,因为我无法找到一种方法来迭代列表中的列表,如下面的伪代码

for elem1, elem2, elem3 in list1, list2, list3 do
  Repo.insert{elem1, elem2, elem3}
end

这是我的数据。

@list_of_names      ~w(Daniel Admin Goran Tomislav User1)
@list_of_usernames  ~w(daniel admin goran marex User2)
@list_of_passwords  ~w(123456 000000 123456 123456 123456)

我需要使用User struct插入它。

Repo.insert!(%User{
  name: name, 
  username: username, 
  password: password
})

我已尝试使用docs,但此代码无效。

defmodule Rumbl.DatabaseSeeder do

  alias Rumbl.Repo
  alias Rumbl.User



  @list_of_names      ~w(Daniel Admin Goran Tomislav Marin)
  @list_of_usernames  ~w(daniel admin goran marex marin)
  @list_of_passwords  ~w(123456 000000 123456 123456 123456)

  def insert_user do
    Repo.insert!( %User{
      name:     (@list_of_names     |> Enum.take_random), 
      username: (@list_of_usernames |> Enum.take_random), 
      password: (@list_of_passwords |> Enum.take_random)
    })
  end
end
(1..5) |> Enum.each(fn _ -> Rumbl.DatabaseSeeder.insert_user end) 

错误:mix run priv\repo\seeds.exs

** (UndefinedFunctionError) function Enum.take_random/1 is undefined or private. Did you mean one of:

      * take_random/2

    (elixir) Enum.take_random(["Daniel", "Admin", "Goran", "Tomislav", "Marin"])
    priv/repo/seeds.exs:27: Rumbl.DatabaseSeeder.insert_user/0
    (elixir) lib/enum.ex:657: anonymous fn/3 in Enum.each/2
    (elixir) lib/enum.ex:1628: anonymous fn/3 in Enum.reduce/3
    (elixir) lib/range.ex:92: Enumerable.Range.reduce/5
    (elixir) lib/enum.ex:1627: Enum.reduce/3
    (elixir) lib/enum.ex:656: Enum.each/2
    (elixir) lib/code.ex:363: Code.require_file/2
    (mix) lib/mix/tasks/run.ex:71: Mix.Tasks.Run.run/1
    (mix) lib/mix/task.ex:296: Mix.Task.run_task/3
    (mix) lib/mix/cli.ex:58: Mix.CLI.run_task/2
    (elixir) lib/code.ex:363: Code.require_file/2

1 个答案:

答案 0 :(得分:3)

您可以使用grid.getColumn("Col. Name").setRenderer(new ButtonRenderer(new RendererClickListener() { @Override public void click(RendererClickEvent event) { MyJooqRecord record = (MyJooqRecord) event.getItemId(); //code ... } })); 两次压缩3个列表,然后使用Enum.zip/2迭代它们。

假设此代码位于for之类的exs文件中:

priv/repo/seeds.exs

如果Elixir有names = ~w(Daniel Admin Goran Tomislav User1) usernames = ~w(daniel admin goran marex User2) passwords = ~w(123456 000000 123456 123456 123456) for {{name, username}, password} <- name |> Enum.zip(usernames) |> Enum.zip(passwords) do Repo.insert!(%User{ name: name, username: username, password: password }) end 函数来压缩3个列表,那就更清楚了,但事实并非如此。