Rails Controller 中带有 URL 参数的渲染操作

发布于 2025-01-17 22:22:52 字数 482 浏览 2 评论 0 原文

在我的场景中,我在 URL

localhost:3000/products/new?product_type='abc'

上有一个表单,当我填写表单并点击“保存”时,由于验证错误,它将运行 Rails 块:如下:

format.html {
  render :new,
  status: :unprocessable_entity
}

它将浏览器渲染到 localhost:3000/products/new

但就我而言,我想渲染到我开始的同一页面以及用户填写的 Product表格..

什么可能是最好的解决方案,以便用户应该保留在上一页以及 url 中的数据和参数。

作为

localhost:3000/products/new?product_type='abc'

提前致谢

In my scenario I have a form at a URL

localhost:3000/products/new?product_type='abc'

When I fill the form and hit save, due to validation error it runs the block of rails as follows:

format.html {
  render :new,
  status: :unprocessable_entity
}

and it renders the browser to localhost:3000/products/new

But in my case I want to render to the same page where I started along with the data user has filled in the Product Form..

What could be the best possible solution so user should stay on the previous page along with the data and params in url.

as

localhost:3000/products/new?product_type='abc'

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单爱 2025-01-24 22:22:52

如果您想在任何形式提交后要留在页面上,这很简单,您必须使用

<%= form_with(@product, remote: true) do |f| %>
  ...
<% end %>

在这里您可以看到我通过 远程:true 作为其他参数,将您的表单作为ajax请求发送为ajax请求,而不是刷新当前表单页面。

返回JSON作为错误响应:

format.json { render json: @product.errors, status: :unprocessable_entity }

您还可以使用 page.js.erb 扩展程序创建一个页面,以处理您的JavaScript代码。

That's very simple If you want to stay in page after any form submission you have to use Rails "Ajax helpers"

<%= form_with(@product, remote: true) do |f| %>
  ...
<% end %>

Here you can see I pass remote: true as additional params that will send your form as Ajax request instead for refresh current form page.

Return Json as error response:

format.json { render json: @product.errors, status: :unprocessable_entity }

You can also create a page with page.js.erb extension to handle your javascript code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文