8

I just started with RoR and have a question: How can I insert the current timestamp (or any type of time) into the model? Below you see the log function create.

def create
    @log = Log.new(params[:log])

    respond_to do |format|
      if @log.save
        format.html { redirect_to @log, notice: 'Log was successfully created.' }
        format.json { render json: @log, status: :created, location: @log }
      else
        format.html { render action: "new" }
        format.json { render json: @log.errors, status: :unprocessable_entity }
      end
    end
  end
1
  • Did you create the model using the rails generator? Commented Mar 15, 2013 at 0:33

2 Answers 2

25

The Rails model generator automatically creates created_at and updated_at datetime fields in the database for you. These fields are automatically updated when a record is created or updated respectively.

If you want to manually create a timestamp, add a datetime column (e.g. timestamp_field) to the database and use a before_save callback in your model.

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

But I would insert the timestamp.
Don't you need to write self.timestamp_field = DateTime.now?
@DonKirkby I believe so, as timestamp_field is currently defined as a local variable and as far as I know, ActiveRecord doesn't assume anything about variable names matching class attributes. So, one would need to preface with self as you have suggested, or make it an instance variable by prefacing with @. Then again, I've never encountered this scenario, just speculating.
Should you not use self.touch(:timestamp_field) instead?
5

Using the rails generator e.g rails generate model Log rails creates two timestamp fields automatically for you.

created_at and updated_at both of these fields will be filled by Rails when you create a new record doing Log.new then save on that record or Log.create The updated_at field gets updated only when you update the record's attributes or when you use the method touch on an instance of the model.

Now, if you wanted to create another field with the timestamp type you could make a migration that adds a column to your model like this

rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp

This will generate a migration that will add a column named my_timestamp_field with a timestamp type, just like the created_at and updated_at

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.