问题描述
我有一个使用Devise进行用户身份验证的 Rails 应用程序,但我想在平台中跟踪用户在线的时间。我想在用户表中有一列,以节省该用户的在线时间(小时,分钟..)。例如,一个用户总共在线2个小时,另一个用户15分钟...
I have a Rails application using Devise for authenticate users but I want track the time for users online in the platform. I would like have a column in user table which save the time online for this user (hours, minutes..). For example, one user was online 2 hours in total, another user 15 minutes...
此功能是否存在一些gem或Devise方法?
Does exist some gem or Devise method for this functionality?
先谢谢了。
推荐答案
由于 DEVICE 在线
时,c $ c>会存储 last_sign_in_at
。
您可以执行以下操作。
将迁移
添加到更改用户表并添加字段, total_online_time
Add a migration
to change users table and add a field, total_online_time
rails g migration add_total_online_time_to_users total_online_time:浮动
rails g migration add_total_online_time_to_users total_online_time:Float
向应用程序控制器添加操作前回调以检查用户操作:
Add a before action callback to your application controller to check user actions:
before_action:set_online_time,如果:proc {user_signed_in? }
before_action :set_online_time, if: proc { user_signed_in? }
通过这种方法,我将得到 last_sign_in_at
,因为我有当前时间,所以我会得到这些时间的差值,并以分钟和秒的形式存储在 DB
中。
In this method, I will get last_sign_in_at
and as I have current time, I will get the difference of these times and store in the DB
as minutes and seconds.
同样,如果他登录,我会将这个时间添加到旧时间。
Again, if he login, I will add this time to old time.
当前,我正在保存分钟和秒。由于我无法直接添加两次。
编辑:
我节省了几分钟,因为如果我们在数据库中保存字符串或时间,就无法在旅途中添加最后一个值加上当前值。
I am saving in minutes because, if we save string or time in Database, we cannot add the last value plus the current value on the go. So it the case.
def set_online_time
start_time = current_user.last_sign_in_at.to_time;
end_time = Time.now;
if(start_time && end_time)_
minutes = time_diff(start_time, end_time)
if(current_user.total_online_time)
minutes = current_user.total_online_time + minutes
current_user.update_attribute(:total_online_time, minutes)
end
end
这里是操纵时间的方法:
HEre is the method to manipulate time:
private
def time_diff(start_time, end_time)
(start_time - end_time) / 60
end
现在,从 DB
中检索分钟并转换为 HH:MM:SS
Now, retrieve the minutes from DB
and convert to HH:MM:SS
这是这里的方法,
时间。 at(seconds).utc.strftime(%H:%M:%S)
Time.at(seconds).utc.strftime("%H:%M:%S")
因此, Time.at((current_user.total_online_time)* 60).utc.strftime(%H:%M:%S)
是您的。
So, Time.at((current_user.total_online_time) * 60).utc.strftime("%H:%M:%S")
is yours.
这里是一个例子:
time1 = Time.now => 2017-01-27 18:01:42 +0530
time2= Time.now - 4.hours => 2017-01-27 14:02:02 +0530
minutes = time_diff(time1,time2) => 239.66325946553334
Time.at((minutes) * 60).utc.strftime("%H:%M:%S") => "03:59:39"
So, "03:59:39" is the online time.
注意:
1)这个答案会持续增加用户每次登录时的在线时间。
1) This answer keeps on incrementing the online time of the user whenever he logs in.
2)如果只想最后一次,请使用
2) If you want only the last time, just use,
minutes = time_diff(start_time, end_time)
current_user.update_attribute(:total_online_time, minutes)
您还可以添加一个额外的字段并节省当前的在线时间。
这篇关于如何跟踪一个用户在线的时间?使用Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!