Ruby-on-rails 如何将时间戳插入到 rails 数据库列中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15422695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:38:33  来源:igfitidea点击:

How to insert timestamp into rails database-column

ruby-on-rails

提问by zyrup

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.

我刚开始使用 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

回答by Richard Brown

The Rails model generator automatically creates created_atand updated_atdatetimefields in the database for you. These fields are automatically updated when a record is created or updated respectively.

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

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

如果您想手动创建时间戳,请将日期时间列(例如timestamp_field)添加到数据库并before_save在您的模型中使用回调。

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end

回答by Leo Correa

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

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

created_atand updated_atboth of these fields will be filled by Rails when you create a new record doing Log.newthen saveon that record or Log.createThe updated_atfield gets updated only when you update the record's attributes or when you use the method touchon an instance of the model.

created_atupdated_at这两个领域将Rails的,当你创建一个新的记录做填充Log.new,然后save在该记录或Log.createupdated_at只有当你更新记录的属性或当您使用方法字段被更新touch的模型的实例。

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_fieldwith a timestamptype, just like the created_atand updated_at

这将产生一个迁移,将添加一个名为列my_timestamp_fieldtimestamp型,就像created_atupdated_at