Rails - 如何在不更改页面和更新视图的情况下提交表单?

Posted

技术标签:

【中文标题】Rails - 如何在不更改页面和更新视图的情况下提交表单?【英文标题】:Rails - How to submit a form without changing the page and updating the view? 【发布时间】:2021-08-15 12:25:24 【问题描述】:

大家好!

我正在使用 rails 并且在我希望用户执行的步骤中(在同一页面上):

    输入他的地址 Filling the form

    提交表格 Click to submit

    更新视图以显示地址 The view updated

我应该使用 Stimulis 还是 Ajax?我不太明白哪个更有用! 因为我尝试使用简单的 JS,但它不是 DRY 也不是很简单:

// file.js

document.querySelector(".form").addEventListener('submit', function () 
  adress_form = document.querySelector(".adress_form");
  adress_form.style.display="none";
  document.location.reload();
  display_adress = document.querySelector(".display_adress");
  display_adress.style.display = "block";
);
#file.html.erb

<div class="display_adress">
  <% if current_user.line1? && current_user.postal_code? && current_user.city? %>
    <p>Mon adresse actuel : <%= current_user.line1 %>, <%= current_user.city %> <%= current_user.postal_code %></p>
  <% end %>
</div>
<div class="address_form">
  <%= simple_form_for(current_user, remote: true, html:  id: "addddd") do |f| %>
  <%= f.input :line1, label: 'Mon adresse' %>
  <%= f.input :city, label: 'Ville' %>
  <%= f.input :postal_code, label: 'Code Postal' %>
  <%= f.submit %>
  <% end %>
</div>

要恢复,我希望用户在表单上输入他的地址、提交、更新我的数据库并使用用户提交的新地址更新视图

感谢您的帮助!

【问题讨论】:

【参考方案1】:

您可以在控制器 javascript 中响应。例如: file.html.erb

<%= simple_form_for(current_user, remote: true, format: :js, html:  id: "addddd") do |f| %>

users_controller.rb

def create
  # do your business logic
  render 'create
end

users/create.js.erb

document.getElementById("formId").innerText = "Othe html text or you can call render(*)"

【讨论】:

非常感谢Деревянко Сергей!它可以工作,但是如果我想在另一个视图中使用另一个字段更新(或创建)我的用户,在 users/create.js.erb 中创建的 js 将再次被调用:/ 此外,当我手动刷新时,信息不是持久的页面...有解决该问题的方法吗? :) 您想在传统后端制作动态前端(spa 页面、后端请求)。最佳实践是分别开发front(react、vue、angular等)和beckend(rest-api、graphql等)。在传统后端实现这样的操作非常困难和混乱,并且需要提供特殊的库(在 Rails 上反应或其他东西),如果你想对某一点提出类似的请求(例如更新用户),你应该在api_controllers

以上是关于Rails - 如何在不更改页面和更新视图的情况下提交表单?的主要内容,如果未能解决你的问题,请参考以下文章

在 ruby​​ rails html 视图中使用 Ajax 表单更改图标“like”按钮类

Rails 5 和设计:如何在不更改默认策略的情况下禁用基于令牌的策略上的会话

颤振:如何在不按按钮的情况下进行列表视图更新?

Ajax 和 Rails 4:创建实例变量并更新视图而不刷新

如何在不重绘整个视图的情况下更新 NSView 的一部分

如何在不重新加载页面的情况下更新从 firestore 检索到的标记在我的地图上?