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

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

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 

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 

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

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

现在,如果要创建具有时间戳类型的另一个字段,则可以进行迁移,以便像这样向模型添加列

 rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp 

这将生成一个迁移,它将添加一个名为my_timestamp_field的列,其中包含timestamp类型,就像created_atupdated_at