如何使用一个带有 rails 和 javascript 的提交按钮提交两个表单

How to submit two forms with one submit button with rails and javascript

本文关键字:提交 表单 按钮 javascript 两个 何使用 一个 rails      更新时间:2023-09-26

我需要允许用户在要求他们提供帐户详细信息之前键入评论并提交。提供这些详细信息后,它们将用于创建新用户,并且他们编写的评论也会提交并属于该新用户。目前,我根本无法弄清楚如何在两个表单上触发提交操作,将所有信息传递给服务器以执行这些任务。

基本上我想要的:

  • 用户写评论,提交
  • "提交"按钮显示联系信息表单
  • 用户填写此内容,提交
  • 提交两种表格的数据

我有什么:

_feedback.html.erb

  <%= simple_form_for [@post, Comment.new] do |f| %>
      <%= f.input :body, :label => false, :input_html => { :maxlength => '500', :rows => '4', :placeholder => '...'}  %>
      <% if current_user.guest != true %>
        <%= f.button :submit, "Submit" %>
      <% end %>
  <% end %>
  <% if current_user.guest == true %>
    <input type="submit" value="Submit" onclick="contactDisplay()"></input>
  <% end %>

显示.html.erb

<% if current_user.guest == true %>
  <div id="contact" class="post-contact">
    <%= simple_form_for(@user, :html => { :multipart => true }, defaults: { label: false, required: true }) do |f| %>
      <%= f.input :name, :input_html => { :placeholder => 'Your Name', :id => 'name'} %>
      <%= f.input :email, :input_html => { :placeholder => 'Your Email', :id => 'email'} %>
    <% end %>
    <input type="submit" value="Submit" onclick="submitContact()"></input>
  </div>
<% end %>
<%= render 'posts/show/feedback' %>

帖子.js

function contactDisplay(){
var contact = document.getElementById('contact'); 
    contact.style.display='block';
}
function submitContact(){
    document.getElementById("new_comment").submit();
    document.getElementById("new_user").submit();
}

您可以使用嵌套表单:)这是关于如何做到这一点的轨道广播http://railscasts.com/episodes/196-nested-model-form-part-1