Rails:保存对象后,计算时差并保存为整数

时间:2017-01-28 02:35:59

标签: ruby-on-rails ruby ruby-on-rails-4

当用户去保存活动(下面的架构)时,我想更新模型上的列,其中包含创建活动(created_at)和更新(updated_at)之间的分钟数。

架构:

create_table "activities", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "student_id"
    t.string   "status"
    t.integer  "user_id"
    t.integer  "minutes_out"
    t.index ["student_id"], name: "index_activities_on_student_id"
    t.index ["user_id"], name: "index_activities_on_user_id"
  end

activities_controller.rb

class ActivitiesController < ApplicationController
  before_save :set_minutes_out

  ...

  private
      def set_minutes_out
         activity.minutes_out = (activity.created_at - activity.updated_at).to_i.abs
         activity.save!
      end

1 个答案:

答案 0 :(得分:0)

在带有after_update的模型中会发生这种情况:

activity.rb

after_update :save_minutes_out
  ...
def save_minutes_out
  created_at = self.created_at
  updated_at = self.updated_at
  seconds_out = (created_at - updated_at).to_i.abs
  minutes_out = (seconds_out / 60)
  if (minutes_out = 0)
    minutes_out = 1
  end
  update_column :minutes_out, minutes_out
end