如何通过link_to与Rails从页面上的其他字段提交值?

这是我想要做的:

 "forms[0]['user_brand_role_role_id'].value", :method => "POST", :remote => true %> 

我知道这不起作用。 我想远程调用控制器方法,包括作为参数在除被点击之外的字段中选择的值。

如何使用Javascript引用link_to中的其他字段? 或者还有另一种策略更好吗?

好的,不显眼的javascript时间,基于我的其他答案的评论。

我从我的一个项目中抓住了这个,所以你可能需要根据自己的需要定制它,但它应该让你知道该怎么做。 jQuery 1.3.2,仅供参考。

  $('form.link_id').livequery('submit', function(){ $.ajax({ url: $(this).attr('action'), data: $(this).serializeArray(), type: 'POST', error: function(xhr, status, error){ alert("Save failed. Please check the form and try again.\n" + (error || status)); }, success: function(content){ // do something with reply if you want. }, dataType: 'html' }); return false; }); 

然后,链接是非常基本的:

  

如果您正在使用原型或jQuery,那么类似的东西将访问字段中的值:

 $('#id-of-field').val() # or value() depending on your js 

所以,将它添加到:with语句中:

 :with => "'role_id=' + $('#user_brand_role_role_id').value() + '&other_value=' + $('#id_of_other_thing').value()" 

您可以在JS控制台中进行游戏以获得正确的输出,然后将其放入link_to语句中。

早期版本的rails中的link_to_remote可以解决您的问题。 但是从rails3中,link_to_remote不再存在,因为它们远离了突兀的javascript。 但是你可以使用一个link_to_function ,它可以调用一个javascript函数来为你做get。 请参阅link_to语法与rails3(link_to_remote)和基本的javascript无法在rails3应用程序中工作? 这个讨论更多细节。