22

I read through the techy definition of hidden_fields, but am not sure what it really does. My understanding is that it allows you to pass in an attribute for certain parameters. For example, if you have a rich join model, you can use the hidden_field to assign the user_id to the join model attribute for user. Is that correct?

If so, would it be better to do it in the form or the controller?

noob
  • 1,807
  • 2
  • 18
  • 34

2 Answers2

37

Both of those methods are helpers to create an HTML input tag of type "hidden", and yes, those are used to add parameters to a request (typically a form POST). Really the parameter can be any piece of information you want to send along with a request. Be careful, though, as hidden fields are easily tampered with.

Here's an example that will send a user id in a hidden field

# Form
<%= form_tag foo_path do %>
  <%= hidden_field_tag "user_id", @user.id %>
  ....
  <%= submit_tag "Click Me" %>
<% end %>

# Controller
def foo
  # params[:user_id] is set with the value from the hidden field
  # Do useful stuff with the POST data
end

While you can pass things such as user_id's like this, I find that the need for it is rare. If a user_id is always required for a given situation you might consider using nested routes http://guides.rubyonrails.org/routing.html#nested-resources.

Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
  • Thanks @wizard of ogz. I thought `hidden_field` would not be safe. I am trying to save it via the controller in the `create` method, but am encountering trouble. When you make associations via rich join models, are they supposed to update things like user_id automatically? If so, I am obviously doing something wrong with my associations. Thanks. I also posted another question here: [question](http://stackoverflow.com/questions/7740873/nested-attributes-not-saving-the-user-id-in-join-table) if you want to take a look. Thanks. – noob Oct 12 '11 at 13:36
  • Ah, I think the problem is better explained in the other question, I'll post there – Wizard of Ogz Oct 12 '11 at 14:08
16

It would generate a hidden type of input field...

<input type="hidden" />

This is a way to store information that you want submitted with the form without having to have a visible field.

From the documentation:

hidden_field_tag 'tags_list' generates...
<input id="tags_list" name="tags_list" type="hidden" />

hidden_field_tag is meant to be used without a model whereas hidden_field is meant to be used in conjunction with a form_for call and a model.

hidden_field(:signup, :pass_confirm) generates...
<input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />

Chad Moran
  • 12,834
  • 2
  • 50
  • 72