使用变量Struct

时间:2016-04-26 13:43:09

标签: elixir

我正在努力写下DRY Elixir,戴夫托马斯的书还在帖子里!

下面您将看到为Card自动生成的Phoenix控制器的一部分。在实践中,我有各种与Card完全相同的产品,所以我想概括一下。我的一个努力是在下面,但它没有编译,错误在** {} **。

我很确定我犯了一个根本性的错误,因为我是这门语言的新手(但不是函数式编程)。

  alias Api.Card

  map = %{"cards" => Card, "books" => Book}

  def create(conn, %{"product" => product}) do

    # changeset = Card.changeset(%Card{}, card_params)
    changeset = map[product].changeset(%map[product]**{}**, card_params)

    case Repo.insert(changeset) do
      {:ok, product} ->
        conn
        |> put_status(:created)
        |> put_resp_header("location", card_path(conn, :show, card))
        # |> render("show.json", card: card)
        |> render("new_key.json", id: product.id)

如果您能帮助我,请注意我也需要将card_path转换为变量,但我认为这将与estimate_path product一致。

我也试过这个,但也没有成功

  (Struct, path) =
    case product do
        "cards" -> (Card, card_path)
        _ -> (Card, card_path)
    end

1 个答案:

答案 0 :(得分:3)

如果要创建一个空结构(使用默认值),可以在模块上调用自动生成的__struct__/0函数。

更改

changeset = map[product].changeset(%map[product]**{}**, card_params)

changeset = map[product].changeset(map[product].__struct__, card_params)

要在变量中存储card_path函数,至少有两个选项:

  1. 使用path = &card_path/3存储对该功能的引用,然后将其称为path.(conn, :show, card)

  2. 将其存储为原子,如path = :card_path并使用apply/3来调用它:apply(YourApp.Router.Helpers, path, [conn, :show, card])