remote select, controller needs more form data

偶尔善良 提交于 2019-12-04 21:53:42

I came up with the following solution after reading the jquery_ujs.js file. Apparently, the data that is present in the data-params attribute of the select tag is added to the data that is send to the controller using the ajax request, and at the very beginning of the preparation of the ajax request the 'ajax:before' event is triggered on the select element. I use this event to read the data from the form, serialize it and put it in the data-params tag of the select element. This data is then automatically added in the ajax request. Here is my code:

$(".add_form_data").on('ajax:before', function(event){
    var form = $(this).closest('form');
    var formData = form.serialize();
    $(this).data("params",formData);
});

The only thing left to do is to add the add_form_data class to both select elements.

<%= f.collection_select :model1, Model1.all, :id, :name, "data-remote" => true, "data-url" => "/model3/get_rest_form" :class => "add_form_data"  %>
<%= f.collection_select :model2, Model2.all, :id, :name, "data-remote" => true, "data-url" => "/model3/get_rest_form" :class => "add_form_data" %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!