Rails ajax form not submitting from within another

青春壹個敷衍的年華 提交于 2019-12-11 03:08:31

问题


I have a Rails 3.2 ajax form that creates a new Room for a Hotel. The new Room ajax form works correctly on the Room index page, but once I embed the new Room ajax form on a Hotel edit page, the form is submitted normally without using Ajax.

To create the new Room form, I use the following link on the Hotel edit.html.erb page:

<%#= link_to 'Add a Room', new_room_path(:hotel_id => @hotel.id), :remote => true, :class => 'new_room' %>

This loads the following form partial on to that same page:

<%= form_for @room, :remote => true, :html => { :class => "remote-form" } do |f| %>
 <%= f.text_field :number %>
 <%= f.text_field :size %>

  <% if(params.has_key?(:'hotel_id')) %>
    <% @hotel_id = params[:hotel_id] %>
    <%= f.hidden_field :hotel_id, :value => @hotel_id %>                    
  <% else %>
    <%= f.collection_select(:hotel_id, Hotel.all, :id, :name) %>
  <% end %>

 <%= f.submit "Add this room", :class => 'room_create' %>
 <%= link_to 'Cancel', '#', :class => "room_cancel" %>
<% end %>

And finally, I have the following in my create.js.erb (inside the rooms folder):

alert('Test creating a room');
var content = $('<%= escape_javascript(render(@room)) %>');
$("#room_list tbody").append(content);

The create.js.erb is not executed and the form is submitted regularly (non-ajax) and I finally arrive on the room show.html.erb page.

Why is the form be working correctly on the Units index page, but not on the associated Hotel edit page?


回答1:


Even when you set :remote => true, Rails generates a form tag. Nested form tags are not supported by browsers and will result in unpredictable behavior.

You should rethink the views architecture here. Probably you can have the forms for the rooms outside of the form for the hotel, or maybe you can use fields_for and accepts_nested_attributes_for to edit children objects.

Here's a full example on how to use nested attributes: Nested Attributes Examples.




回答2:


You cannot nest a form inside a form in HTML. When you click any submit button on a form, even if it's inside another form, only the outermost form will be properly submitted.

You can either use nested attributes to add the attributes for the room directly to the form, so that when the overall form is submitted so are all the rooms... or use a div and a link, instead of a form and a submit button.



来源:https://stackoverflow.com/questions/15845741/rails-ajax-form-not-submitting-from-within-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!