153

I wanna do something like this in rails

Here is what I have so far in rails:

<%= form_for @order do |f| %>
  <%= f.hidden_field :service, "test" %>
  <%= f.submit %>
<% end %>

But then I get this error:

undefined method `merge' for "test":String

How can I pass values in my hidden_field in rails?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Jake
  • 1,637
  • 2
  • 12
  • 10

6 Answers6

419

You should do:

<%= f.hidden_field :service, :value => "test" %>

hidden_field expects a hash as a second argument

apneadiving
  • 114,565
  • 26
  • 219
  • 213
55

You are using a hidden_field instead of a hidden_field_tag. Because you are using the non-_tag version, it is assumed that your controller has already set the value for that attribute on the object that backs the form. For example:

controller:

def new
  ...
  @order.service = "test"
  ...
end</pre>

view:

<%= form_for @order do |f| %>
  <%= f.hidden_field :service %>
  <%= f.submit %>
<% end %>
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
user132447
  • 1,651
  • 13
  • 6
27

It works fine in Ruby 1.9 & rails 4

<%= f.hidden_field :service, value: "test" %>
lulalala
  • 17,572
  • 15
  • 110
  • 169
Tushar Patil
  • 1,419
  • 1
  • 18
  • 21
3

A version with the new syntax for hashes in ruby 1.9:

<%= f.hidden_field :service, value: "test" %>
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
2

This also works in Rails 3.2.12:

<%= f.hidden_field :service, :value => "test" %>

bradmalloy
  • 21
  • 5
0

By the way, I don't use hidden fields to send data from server to browser. Data attributes are awesome. You can do

<%= form_for @order, 'data-service' => 'test' do |f| %>

And then get attribute value with jquery

$('form').data('service')
Alex Teut
  • 844
  • 9
  • 20