9

Is there a way to capture the querystring and send that along as part of a form post? I'm using Rails 2.3.5 and my user is on a page that has multiple querystring parameters. On this page, they are going to submit a form. Inside the action that receives the post, I want to know what those querystring parameters were. Obviously, they are not sent as part of the post. So I need the actual form values, plus the querystring params that were on the page when the user submitted the form.

I'm sure I could write some nasty javascript that would shove the querystring params into hidden fields on the form so they would be available, but that seems ugly. My Googling hasn't turned up much, which makes me wonder if I'm just going about this all wrong. To make matters worse, I'm a Rails newbie.

Appreciate any pointers or ideas to get me going in the right direction.

Mark Hoffman
  • 413
  • 5
  • 10

4 Answers4

9

A friend of mine showed me what I believe is an easier way:

<% form_tag params.merge(:action=>"someAction") do %>

Merging params into the hash necessary for making the form_tag did the trick perfectly.

Mark Hoffman
  • 413
  • 5
  • 10
  • yep that's better since it does in fact create the url querystring – jpw Jul 28 '12 at 22:08
  • Beware: browsers ignore query strings for GET requests, in that case you'll have to create hidden fields for each input. – fny Feb 07 '13 at 06:39
  • 4
    To clarify @faraz 's statement: browsers ignore query strings in the **action** URL for forms which submit with the GET method – Jordan Sitkin May 23 '13 at 18:48
5

The preferred way would be to use hidden fields. I haven't tried it, but I think you can specify additional query string parameters within the *_path or *_url helpers. Something like:

<% form_for(@post,
           :url => post_path(@post, :foo => 'foo', :bar => 'bar')) do |f| %>
  ...
<% end %>
John Topley
  • 113,588
  • 46
  • 195
  • 237
0
<% form_tag params.merge(:action=>"someAction") do %>

- No route matches [POST]

Tunaki
  • 132,869
  • 46
  • 340
  • 423
0

Use hidden_field_tag if you're using a GET request.

In our case we were using a simple form with a select for setting the Per Page values for pagination. We found that any existing GET params were cleared when submitting this form. To fix this we used hidden_field_tags in our form.

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

form_content = request.query_parameters.collect do |key, value|
  hidden_field_tag key, value
end

This will ensure that your existing params persist.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245