gpt4 book ai didi

redirect - 'halt' (Plug.Conn.halt/1) 在 Controller 重定向后不会停止调用链

转载 作者:行者123 更新时间:2023-12-05 00:18:06 27 4
gpt4 key购买 nike

我在基于某些逻辑的 Controller 中有一个“halt/1”,但不是在插头中。可悲的是,它确实重定向,但也在重定向后运行代码。

if true do
conn
|> put_flash(:error, "Sorry, entered wrong")
|> redirect(to: route_path(conn, :show, model))
|> halt #this does not work :(
else
_ #something
end

update_another_model() #this is executed
render(conn, "abc.html", model: model) #even this is executed

我实际上需要在重定向后终止调用,有什么想法吗?

最佳答案

没有return在 Elixir 中 - 您不能提前退出函数。如果你需要,那么重构你的 if这样所有不需要执行的语句都在else中分支。

if condtition() do
conn
|> put_flash(:error, "Sorry, entered wrong")
|> redirect(to: route_path(conn, :show, model))
else
update_another_model()
render(conn, "abc.html", model: model)
end

condition()true第一个分支执行,结果 redirect返回(指示重定向的响应)。如果是 false然后第二个分支返回 render 的结果.

另请注意,如果 if 后面有任何内容然后无论采用哪个分支,它都会被执行,并且该操作的结果将从操作中返回 - 可能不是您想要的。

关于redirect - 'halt' (Plug.Conn.halt/1) 在 Controller 重定向后不会停止调用链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com