user3711600
user3711600

Reputation: 873

set param value in rails form_for method

How can I set the value of an attribute (called 'type') that I don't want to appear in a form? (i.e. I don't want the user to be able to select it in the form. I want to set the value myself).

My form code is:

<%= form_for @unit do |f| %>

     <%= f.datetime_select :start_datetime %>
     <%= f.text_field :notes %>

<% end %>

This generates params of:

{'unit' => {'start_datetime' => value, 'notes' => value }}

I want to set the 'type' attribute (to some value that I determine) so that the form returns params of:

{'unit' => {'type' => value, 'start_datetime' => value, 'notes' => value }}

Does form_for have some option that I can use to include 'type' in params and set its value?

Upvotes: 2

Views: 2134

Answers (2)

Pavan
Pavan

Reputation: 33542

You can pass it with hidden_field like this

<%= f.hidden_field :type,:value=>"some_value" %>

<%= form_for @unit do |f| %>
  <%= f.hidden_field :type, :value => "some_value" %>
  <%= f.datetime_select :start_datetime %>
  <%= f.text_field :notes %>
<% end %>

Upvotes: 2

Mandeep
Mandeep

Reputation: 9173

You need to use hidden_field inside your form_for like:

<%= form_for @unit do |f| %>
  <%= f.hidden_field :type, :value => "your_value" %>
  <%= f.datetime_select :start_datetime %>
  <%= f.text_field :notes %>
<% end %>

which will give you params like:

{'unit' => {'type' => value, 'start_datetime' => value, 'notes' => value }}

Upvotes: 2

Related Questions