Elixir 简化Phoenix控制器操作
在我的Phoenix应用程序中,我在controller中有以下操作:Elixir 简化Phoenix控制器操作,elixir,phoenix-framework,Elixir,Phoenix Framework,在我的Phoenix应用程序中,我在controller中有以下操作: 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"
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)
有没有办法重构它?
在RubyonRails中,我将使用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
它在display.TopicController.set\u topic/2中返回
没有匹配的函数子句。这是因为set_topic
无权访问请求参数。有什么想法吗?但如果你只有一行重复的话,它就不会短了。@Dogbert谢谢你的回复。我还是不能让它工作。我更新了我的帖子。我相信插件调用的函数接受不同的参数,请查看docs@MateuszUrbański TryRepo.get!(主题,conn.params[“id”])
并忽略函数的第二个参数。就像@JustMichael所说的,plugs不会将params作为第二个参数(这个答案很可能不正确)。或者使用模式匹配def set\u-topic(conn=%{params:%{id=>topic\u-id},{code>)。