Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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
share|improve this question
    
can you post the Timesheet table from your schema? – Rocco Mar 21 at 19:18
    
i added my schema – Ben Mar 21 at 19:21
    
Is it possible you're overriding the time method in the model? – Isaac Betesh Mar 21 at 19:27
    
time might also be reserved by rails – Rocco Mar 21 at 19:36
    
@Rocco time is not reserved - but in is a Ruby reserved word. – max Mar 21 at 19:47
up vote 0 down vote accepted

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).

share|improve this answer
    
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 if you want to do it like a rockstar. – max Mar 21 at 19:46
    
How would I change the name of the column using a migration file? – Ben Mar 21 at 19:59
1  
stackoverflow.com/questions/471416/… Google 'n stuff – SirUncleCid Mar 21 at 20:07
    
If you have a time column you also need to change the type to datetime – max Mar 21 at 21:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.