【问题标题】:How to insert timestamp into rails database-column如何将时间戳插入到 Rails 数据库列中
【发布时间】:2016-11-08 17:24:21
【问题描述】:

我刚开始使用 RoR 并且有一个问题:如何将当前时间戳(或任何类型的时间)插入模型中?下面你会看到日志函数 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

【问题讨论】:

  • 您是否使用 rails 生成器创建了模型?

标签: ruby-on-rails


【解决方案1】:

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

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

class Log < ActiveRecord::Base
  before_save :generate_timestamp

  def generate_timestamp
    self.timestamp_field = DateTime.now
  end
end

【讨论】:

  • 但我会插入时间戳。
  • 不需要写self.timestamp_field = DateTime.now吗?
  • @DonKirkby 我相信是这样,因为timestamp_field 目前被定义为一个局部变量,据我所知,ActiveRecord 不假设任何与类属性匹配的变量名。因此,需要按照您的建议以self 开头,或者通过以@ 开头使其成为实例变量。再说一次,我从来没有遇到过这种情况,只是猜测。
【解决方案2】:

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

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

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

rails generate migration add_some_timestamp_field_to_logs my_timestamp_field:timestamp

这将生成一个迁移,该迁移将添加一个名为 my_timestamp_field 的列,其类型为 timestamp,就像 created_atupdated_at 一样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2013-05-27
    • 2016-03-06
    • 2014-02-02
    • 2011-03-26
    • 1970-01-01
    相关资源
    最近更新 更多