简化Phoenix控制器操作

时间:2017-02-05 14:41:35

标签: elixir phoenix-framework

在我的Phoenix应用程序中,我在控制器中执行以下操作:

  def edit(conn, %{"id" => topic_id}) do
    topic = Repo.get(Topic, topic_id)
    changeset = Topic.changeset(topic)

    render conn, :edit, changeset: changeset, topic: topic
  end

  def update(conn, %{"id" => topic_id, "topic" => topic_params}) do
    topic = Repo.get(Topic, topic_id)
    changeset = Topic.changeset(topic, topic_params)

    case Repo.update(changeset) do
      {:ok, _topic} ->
        conn
        |> put_flash(:info, "Topic Updated")
        |> redirect(to: topic_path(conn, :index))

      {:error, changeset} ->
        render conn, :edit, changeset: changeset, topic: topic
    end
  end

这一行在这些函数中重复:

topic = Repo.get(Topic, topic_id)

有没有办法重构它? 在Ruby on Rails中,我将使用before操作,如何在Phoenix中执行此操作?

我尝试过这样的事情:

  plug :set_topic when action in [:edit, :update]

  def set_topic(conn, %{"id" => topic_id}) do
    topic =  Repo.get!(Topic, topic_id)

    assign(conn, :topic, topic)
  end

返回no function clause matching in Discuss.TopicController.set_topic/2。这是因为set_topic无权访问请求参数。有什么想法吗?

0 个答案:

没有答案