Question

I'm writing a search form that will reload the page adding to the URL the search parameters.

Currently the URL generated by my form contains all the form fields, including the empty ones. This clutters a lot the url generated with data that is often not needed.

I would like my form to redirect to an url that only has the fields that contain data.

There's the code for my form:

= 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

When I hit the submit button without filling any of the form I get redirected to an url like this:

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

while I would like the url to be like this:

http://localhost:3000/orders

and if I select only some of the order_types I get:

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

while I would like it to be like:

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

or even better:

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

or something similar, but more concise,

Thanks a lot for any help,

Was it helpful?

Solution

form_for binds the form to an object and rails internals will namespace the fields related to this object (or objects) with a prefix, so that when the form is submitted the data will appear in params as params[:prefix][:some_data].

To reduce the size of the query string I would suggest you to use form_tag and build the form manually. In this way you can have full control over the submitted fields and also avoid the utf8=%E2%9C%93 utf8 enforcement snowmen hack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top