Search code examples
jqueryruby-on-railsruby-on-rails-4ruby-on-rails-3.1

Two forms, one submit rails


I have a problem with that:

My first Form

 <div class="authform">
   <h3>Edit <%= resource_name.to_s.humanize %></h3>
   <%= form_for(current_user, :url => registration_path(current_user ), :html => { :method => :put, :role => 'form', :id => "form1"}) do |f| %>
     <%= devise_error_messages! %>
     <div class="form-group">
       <%= f.label :nombre %>
       <%= f.text_field :nombre, :autofocus => true, class: 'form-control' %>
     </div>
      <div class="form-group">
       <%= f.label :email %>
       <%= f.email_field :email, class: 'form-control' %>
      </div>
     </div>
      <% end %>
 </div>

The Second form is

  <%= simple_form_for(@auto, html: { method: :post, id: :subir }) do |f| %>
    <%= f.error_notification %>

    <div class="form-inputs">
       <%= f.association :region %>
       <%= f.association :ciudad %>
       <%= f.association :marca %>
       <%= f.input :modelo %>
       <%= f.input :version %>
   </div>
  <% end %>

  <%= link_to "Save", edit_user_registration_path, :class => 'button_submit' %>

auto.coffee

 jQuery ->
    $(".button_submit").live "click", (e) ->
      e.preventDefault()
      $("#form1").trigger "submit"
      $("#subir").trigger "submit"

I need this to keep the truth and do not realize that. I'm doing something wrong, please help.

Regards.


Solution

  • It is suggested use only one form. But if u want to use multiple forms in rails you can use semantic form for with semantic nested fields which will help you use multiple forms and also useful to save data with relation. https://github.com/ryanb/nested_form for your reference.

    Modified form like this,

    <%= semantic_form_for current_user, :url => registration_path(current_user ), :html => { :method => :put, :role => 'form', :id => "form1"} do |f| %>
      <%= devise_error_messages! %>
      <div class="form-group">
        <%= f.label :nombre %>
        <%= f.text_field :nombre, :autofocus => true, class: 'form-control' %>
      </div>
      <div class="form-group">
        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>
      </div>
      <%= f.semantic_fields_for(@auto, html: { method: :post, id: :subir }) do |form| %>
        <%= form.error_notification %>
        <div class="form-inputs">
          <%= form.association :region %>
          <%= form.association :ciudad %>
          <%= form.association :marca %>
          <%= form.input :modelo %>
          <%= form.input :version %>
        </div>
      <% end %>
    <% end %>
    

    and also you should have in user model,

     class User < ActiveRecord::Base
        has_many :posts
        accepts_nested_attributes_for :posts, :reject_if => :all_blank, :update_only => true, :allow_destroy => true
      end