When a user goes to save an Activity (schema below), I'd like to update a column on the model with the number of minutes between the time that activity was created (created_at) and updated (updated_at).
Schema:
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
This happens in the model with an 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.