远程选择,控制器需要更多表格数据 [英] remote select, controller needs more form data

查看:419
本文介绍了远程选择,控制器需要更多表格数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有两个选择字段.每当这些选择字段之一更改值时,表格的其余部分都应更改.我将以下代码用于选择字段:

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"  %>

现在的问题是,model3控制器需要两个选择字段的值才能制定对发送给它的Ajax请求的响应,但是它仅获取刚刚在参数中更改的选择字段的值.

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.

如果更改model1字段,我得到:

If the model1 field is changed I get:

params = {"model3"=>{"model1"=>"2"}}

如果更改model2字段,我得到:

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.

谢谢!

推荐答案

阅读

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);
});

剩下要做的就是将 add_form_data 类添加到两个选择元素中.

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" %>

这篇关于远程选择,控制器需要更多表格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆