rails 3 form_tag方法:: get只包含已更改的字段

时间:2013-10-27 14:22:21

标签: ruby-on-rails forms activeview

我正在编写一个搜索表单,用于重新加载页面,将URL添加到搜索参数中。

目前,我的表单生成的网址包含所有表单字段,包括空字段。这会使用通常不需要的数据生成的URL混乱很多。

我希望我的表单重定向到只包含包含数据的字段的网址。

我的表单有代码:

= form_tag orders_path, method: :get do
    = text_field_tag :search, params[:search], class: "span2 appendedInputButtons"
    = select_tag "order_types", 
      options_from_collection_for_select(OrderType.all, :id, :name),
      multiple: true, 
      size: 8, 
      include_blank: "select"
    %button.btn.btn-primary Update list

当我点击提交按钮而没有填写任何表格时,我会被重定向到这样的网址:

http://localhost:3000/orders?utf8=%E2%9C%93&search=&order_types%5B%5D=

虽然我希望网址是这样的:

http://localhost:3000/orders

如果我只选择order_types中的一些,我会得到:

http://localhost:3000/orders?utf8=%E2%9C%93&search=&order_types%5B%5D=3&order_types%5B%5D=6

虽然我希望它像:

http://localhost:3000/orders?order_types%5B%5D=3&order_types%5B%5D=6

甚至更好:

http://localhost:3000/orders?order_types=3,6

或类似的东西,但更简洁,

非常感谢您的帮助,

1 个答案:

答案 0 :(得分:2)

form_for将表单绑定到一个对象,rails内部将使用前缀命名与该对象(或多个对象)相关的字段,以便在提交表单时,数据将显示在params中{{1 }}

要缩小查询字符串的大小,我建议您使用params[:prefix][:some_data]build the form manually。通过这种方式,您可以完全控制提交的字段,还可以避免执行form_tag utf8雪人黑客攻击。