Abhi
Abhi

Reputation: 4261

Passing default params to rails form_for

I have a simple form like:

= form_tag history_path(params), :method => :get do
  = radio_button_tag :history_id, @history.id, true
  History
  %br

  = submit_tag "Get History", class: "btn generate"

Now, params has some extra info like {visit_id: 1, company_id: 32}

Even when I inspect the form I see the action as:

<form action="/history?visit_id=1&company_id=32" accept-charset="UTF-8" method="get">

But, upon clicking submit, the params are never passed, I only get the following params passed (in server log):

Parameters: {"utf8"=>"✓", "history_id"=>"939", "commit"=>"Get History"}

EDIT

I'm aware that I can add them to hidden_field_tag, but the params can be many and I can't keep on adding hidden fields. So, I need to understand why the above way isn't working.

Upvotes: 0

Views: 811

Answers (2)

xploshioOn
xploshioOn

Reputation: 4115

This is not a rails problem, it's just html, because your form has the get method, it will replace all get variables that you have on the url action and let just the ones that are on the form. you can combine this, sending get variables in the url, but with the form as post, not on get. in this case then you have 2 options, use the solution that @Deepak Mahakale sent, or change your form to post, and make the respective changes on the controller and routes.

Upvotes: 3

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

Try adding them as hidden_field_tag

= form_tag history_path(params), :method => :get do
  = hidden_field_tag :visit_id, 1
  = hidden_field_tag :company_id, 32
  = radio_button_tag :history_id, @history.id, true
  History
  %br

  = submit_tag "Get History", class: "btn generate"

And now you will receive the data in params as

Parameters: {"utf8"=>"✓", "history_id"=>"939", "visit_id" => "1", "company_id" => "32", "commit"=>"Get History"}

Upvotes: 2

Related Questions