views:

24

answers:

2

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]
+2  A: 

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  %>
Salil
+1  A: 

include the hidden field with your form builder object 'f'

f.hidden_field :user_id, current_user.id

Suman Mukherjee