0

I have written a rest api in ruby on rails that saves timesheets to a database. Before saving the timesheet, I am trying to set the timesheet's time property to the current time, Time.now. However, the time always gets set to null.

Here is my create method:

    def create
    @timesheet = Timesheet.new
    @timesheet.assign_attributes(@json['timesheet'])
    @timesheet.time = Time.now
    if @timesheet.save
      render json: @timesheet
    else
       render nothing: true, status: :bad_request
    end
  end

I am testing via terminal and I always get json back with time:null. Thanks for any help.

edit: Schema

create_table "timesheets", force: :cascade do |t|
  t.integer  "employer_id"
  t.integer  "employee_id"
  t.datetime "time"
  t.boolean  "in"
end
Jared
  • 578
  • 7
  • 21

1 Answers1

0

Rails already has built in support for timestamps. Why duplicate it if it is already there? By default when you generate a model the migration created will have both the created_at and updated_at columns.

To add timestamps to an existing table you would do:

rails g migration add_timestamps_to_something created_at:datetime updated_at:datetime
rake db:migrate

Replace something with the name of the table you want to alter. As long as the model has these columns rails will set created_at when you create the record and updated_at when the record is updated (duh).

max
  • 96,212
  • 14
  • 104
  • 165
  • On a side note don't use `in` as a column name - it is a reserved word in Ruby and will give a syntax error if you call it without `self`. Use an integer called `status` together with an [enum](http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html) if you want to do it like a rockstar. – max Mar 21 '16 at 19:46
  • How would I change the name of the column using a migration file? – Jared Mar 21 '16 at 19:59
  • 1
    http://stackoverflow.com/questions/471416/how-do-you-write-a-migration-to-rename-an-activerecord-model-and-its-table-in-ra Google 'n stuff – SirUncleCid Mar 21 '16 at 20:07
  • If you have a time column you also need to change the type to datetime – max Mar 21 '16 at 21:55