zyrup
zyrup

Reputation: 717

How to insert timestamp into rails database-column

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

Upvotes: 8

Views: 39661

Answers (2)

Leo Correa
Leo Correa

Reputation: 19789

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

Upvotes: 5

Richard Brown
Richard Brown

Reputation: 11436

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

Upvotes: 25

Related Questions