问题
I have two select fields in a form. Every time one of these select fields change value, the rest of the form should be changed. I used the following code for the select fields:
<%= f.collection_select :model1, Model1.all, :id, :name, "data-remote" => true, "data-url" => "/model3/get_rest_form" %>
<%= f.collection_select :model2, Model2.all, :id, :name, "data-remote" => true, "data-url" => "/model3/get_rest_form" %>
The problem now is that the model3 controller needs the values of both select fields in order to formulate a response to the Ajax request sent to it, but it only gets the value of the select field that has just been changed in params.
If the model1 field is changed I get:
params = {"model3"=>{"model1"=>"2"}}
If the model2 field is changed I get:
params = {"model3"=>{"model2"=>"3"}}
But I need the following in both cases.
params = {"model3"=>{"model1"=>"2", "model2" => "3"}}
How can I realize this?
Maybe there is a way so that all the form data is send when the select fields are changed.
Thank you!
回答1:
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" %>
来源:https://stackoverflow.com/questions/10970454/remote-select-controller-needs-more-form-data