# Datetime field inserted is NULL when value is assigned to model object

**URL:** <https://www.ruby-forum.com/t/datetime-field-inserted-is-null-when-value-is-assigned-to-model-object/144548>\
**Category:** Rails\
**Created:** [July 30, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/datetime-field-inserted-is-null-when-value-is-assigned-to-model-object/144548 "2008-07-30T21:06:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hangingclowns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/b5e925/32.png) [@hangingclowns](https://www.ruby-forum.com/u/hangingclowns)\
**Post date:** [July 30, 2008, 9:06pm UTC](https://www.ruby-forum.com/t/datetime-field-inserted-is-null-when-value-is-assigned-to-model-object/144548/1 "2008-07-30T21:06:11Z")

</div>

This is pretty baffling. I have the following model object:

create\_table “activities”, :force =\> true do |t|  
t.integer “user\_id”, :limit =\> 11  
t.datetime “created\_at”  
t.datetime “updated\_at”  
t.integer “location\_id”, :limit =\> 11  
t.datetime “event\_date”  
end

model/activity.rb:

class Activity \< ActiveRecord::Base

belongs\_to :User  
belongs\_to :Location

attr\_accessor :event\_date  
attr\_accessor :user  
attr\_accessor :location

end

my activities\_controller.rb:

```
activity = Activity.new(params[:activity])

activity.event_date = Date.today

activity.user_id = current_user.id

activity.save

```

It throws an error b/c it’s trying to insert NULL for event\_date in the  
MYSQL database:  
ActiveRecord::StatementInvalid (Mysql::Error: Column ‘event\_date’ cannot  
be null: INSERT INTO `activities` (`update\ d_at`, `location_id`, `user_id`, `event_date`, `created_at`)  
VALUES(‘2008-07-30 05:16:00’, 1, 1, NULL, ‘2008-07-30   
05:16:00’)):

I have no idea why. If I explicitly print out ‘activity.event\_date.to\_s’  
is gives me the date of today.

If I remove the stipulation the “event\_date” can be NULL it just insert  
a NULL value.

thanks in advance for help

---

<div class="post-metadata">

**Author:** ![hangingclowns](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/b5e925/32.png) [@hangingclowns](https://www.ruby-forum.com/u/hangingclowns)\
**Post date:** [July 30, 2008, 9:19pm UTC](https://www.ruby-forum.com/t/datetime-field-inserted-is-null-when-value-is-assigned-to-model-object/144548/2 "2008-07-30T21:19:07Z")

</div>

Quoting Allen W. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> attr\_accessor :location
> 
> I have no idea why. If I explicitly print out ‘activity.event\_date.to\_s’  
> is gives me the date of today.
> 
> If I remove the stipulation the “event\_date” can be NULL it just insert  
> a NULL value.
> 
> thanks in advance for help

datetime is a Time, not a Date. Try activity.event\_date = Time.now.

HTH,  
Jeffrey
