我的 Rails 应用程序中有一个带有非常简单的 Controller 的表单,如果该表单无法保存,我想渲染 :new
以显示错误:
def create
@health_profile = HealthProfile.new(health_profile_params)
if @health_profile.save
redirect_to :somewhere_else
else
render :new
end
end
这效果很好,但在尝试创建记录后,URL 从 /health_profiles/new
变为 /health_profiles
。有没有办法调用 render :new
并使 URL 反射(reflect)用户位于 /health_profiles/new
?如果他们在 URL 显示 /health_profiles
时刷新页面,则会加载 :index
,这不是我想要的。
最佳答案
不是真的。您基本上有三个选择:
您可以use JS to change the URL重新渲染新 View 后。
您可以将
render
更改为redirect_to
,但您会丢失@health_profile
中的错误,因此您可以依靠flash
来显示您的错误。您可以更改所有路由,以便可以 POST/PUT 到
new
路由,并在new
操作中添加一些条件逻辑,以便基于以下条件进行分支request.method
关于ruby-on-rails - 在表单上呈现新错误不会更改 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949847/