我正在使用rails和带有把手的主干,我有一个嵌套的表单。
我正在尝试创建用户,并且用户可以提供网址。 所以我有一个用户模型和一个网址模型
我以为我可以做这样的事情
<form id="new_user"> <label name="username" >username</label> <input type="text" name="username" /> <label name="url" >url</label> <input type="text" class="nested urls_attributes" name="url" /> </form>
---------------------- update ------------------------ -----------------
因为这是很少使用的东西,我在提交表单时更新了我的主干视图以创建正确的json,所以现在在提交表单上,我创建第一个json,然后添加嵌套对象。
var form_json = MyApp.Helpers.Serialize_Form($('form#user_form inputs').not('.nested')); form_json['urls_attributes']=MyApp.Helpers.Serialze_Form($('form#user_form inputs.nested'));
这将以
的格式创建json{username: "test", urls_attributes: {url:"http://test"}}
所以当我将它传递给我的控制器时,我希望在创建用户时创建url。
不幸的是,这似乎没有发生,我没有错误。用户被创建,但不是嵌套的url模型。
知道为什么会这样吗?
-----------我如何制作json ----------------------
我将表单转换为带有
的json对象serialize_objects: function(inputs){ //this takes form inputs and creates a json string of them var o = {}; $.map(inputs, function(t) { if (o[t.name] !== undefined) { if (!o[t.name].push) { o[t.name] = [o[t.name]]; } o[t.name].push(t.value || ''); } else { o[t.name] = t.value || ''; } }); return o; }
我不能使用jquery serializeArray,因为我使用的是没有实现serializeArray的jqMobi。但这对于这个问题无关紧要。