如何将时间戳插入rails database-column

zyr*_*rup 7 ruby-on-rails

我刚开始使用RoR并提出一个问题:如何将当前时间戳(或任何类型的时间)插入模型中?下面你看到日志功能创建.

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
Run Code Online (Sandbox Code Playgroud)

Ric*_*own 22

Rails模型生成器为您自动在数据库中创建 created_atupdated_at datetime字段.分别创建或更新记录时,这些字段会自动更新.

如果要手动创建时间戳,请将datetime列(例如timestamp_field)添加到数据库并before_save在模型中使用回调.

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end
Run Code Online (Sandbox Code Playgroud)


Leo*_*rea 5

使用rails 生成器(例如rails generate model Lograils)会自动为您创建两个时间戳字段。

created_atupdated_at您创建一条新记录时,Rails 将填充这两个字段,Log.new然后save在该记录上执行操作,或者仅当您更新记录的属性或在模型实例上 使用该方法时,Log.create字段才会更新。updated_attouch

现在,如果您想创建另一个具有时间戳类型的字段,您可以进行迁移,将一列添加到您的模型中,如下所示

rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp
Run Code Online (Sandbox Code Playgroud)

这将生成一个迁移,该迁移将添加一个my_timestamp_fieldtimestamp类型命名的列,就像created_atupdated_at