开发者

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?


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.


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.


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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜