Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails forms: How to append request params?

I got a list page and I filter items via links with get params (I can choose many links so query would be like "?param1=value1&param2=value2"). But also I have to filter it by text field, so I made a form:

<form>
  <%= text_field_tag :zip, params[:zip] %>
  <%= submit_tag 'OK', :name => nil %>
</form>

But when I submit it, text field param replaces existing query params. So, how to make text field value add to query, not to replace it?

like image 750
Mikhail Knyazev Avatar asked May 18 '11 18:05

Mikhail Knyazev


3 Answers

Since I was just dealing with this problem in Rails 4 I thought I'd share my solution. My page gets loaded with a sport_id parameter, and when the user specifies a sort-order I wanted it to submit a GET request for page.url/event?sport_id=1&sortby=viewers but it wouldn't preserve the sport_id parameter until I added a hidden field tag in the form like so:

<%= hidden_field_tag :sport_id, params[:sport_id] %>

This solution does submit an empty sport_id parameter if that parameter was not in the original request, but that is easily prevented by encapsulating the hidden field in an <% if params[:sport_id].present? %> condition.

like image 119
pklinken Avatar answered Sep 28 '22 08:09

pklinken


Use hidden_field_tag.

Inside of your form, just set hidden_field_tags for the existing GET params, like so:

<% request.query_parameters.collect do |key, value| %>
  <%= hidden_field_tag key, value %>
<% end %>

This will ensure that your existing params persist.

like image 39
Joshua Pinter Avatar answered Sep 28 '22 07:09

Joshua Pinter


Rails 3?

<%= form_tag your_path(params.except(:controller, :action)), :method => :get do %>
  <%= text_field_tag :zip, params[:zip] %>
  <%= submit_tag 'OK', :name => nil %>
<% end %>
like image 23
fl00r Avatar answered Sep 28 '22 09:09

fl00r