Reputation: 29787
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]
Upvotes: 4
Views: 10689
Reputation: 754
For Rails 4 use:
<%= f.hidden_field :user_id, value: current_user.id %>
Upvotes: 7
Reputation: 18208
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 %>
Upvotes: 20
Reputation: 205
include the hidden field with your form builder object 'f'
f.hidden_field :user_id, current_user.id
Upvotes: 1
Reputation: 47482
USE
<%= f.hidden_field :user_id, current_user.id %>
INSTEAD OF
<%= hidden_field_tag 'user_id', current_user.id %>
Explaination:- In controller probably you doing something like follwing
@entry = Entry.new(params[:entry])
@entry.save #But there is no params[:entry][:user_id] so null is getting saved
So you have to one of the following (othere than one i mention above)
@entry = Entry.new(params[:entry])
@entry.user_id= params[:user_id]
@entry.save
or
<%= hidden_field_tag 'entry[user_id]', current_user.id %>
Upvotes: 16