RoR form_for: Hidden field isn't being included within the object parameter and therefore doesn't work.

ben picture ben · Jul 9, 2010 · Viewed 10.6k times · Source

I'm using a form to add an entry, and I need to send the id of the current user along with the entry parameters. Here is my form code:

<% form_for(@entry) do |f| %>
  <%= f.error_messages %>
<%= hidden_field_tag 'user_id', current_user.id  %>
  <p>
    <%= f.label :date %><br />
    <%= f.date_select :date %>
  </p>
  <p>
    <%= f.label :note %><br />
    <%= f.text_field :note %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

The problem is that user_id is being saved as null. I noticed in the console output below that user_id is present, but it isn't actually located within the entry object parameters. How can I fix this? Thanks for reading.

Processing EntriesController#create (for 127.0.0.1 at 2010-07-09 19:57:55) [POST]
  Parameters: {"commit"=>"Create", "action"=>"create", "user_id"=>"3", "entry"=>{"date(1i)"=>"2010", "date(2i)"=>"7", "date(3i)"=>"9", "note"=>"bb"}, "controller"=>"entries"}
  Entry Create (0.4ms)   INSERT INTO "entries" ("entry_id", "created_at", "updated_at", "date", "user_id", "note") VALUES(NULL, '2010-07-09 09:57:55', '2010-07-09 09:57:55', '2010-07-09', NULL, 'bb')
Redirected to http://localhost:3000/entries/7
Completed in 24ms (DB: 0) | 302 Found [http://localhost/entries]

Answer

Eric Hu picture Eric Hu · Mar 18, 2013

The other answers are written for Rails 2. The Rails 3 adaptation of Salil's answer uses this format:

<%= f.hidden_field :user_id, :value => current_user.id %>