计算rails update中created_at和now()之间的差异

时间:2015-09-14 00:33:44

标签: ruby-on-rails ruby-on-rails-3 postgresql activerecord

我有一个列应该包含created_at和updated_at之间的差异,所以我尝试执行以下操作,但它通常会将time_diff保存为零。那么,我该如何解决这个问题?

Product.update(
    id,
    time_diff: "((EXTRACT (DAY FROM (now()-created_at))*24*60*60+
                    EXTRACT (HOUR FROM (now()-created_at))*60*60+
                    EXTRACT (MINUTE FROM (now()-created_at))*60+
                    EXTRACT (SECOND FROM (now()-created_at)))/60)::int"
  )

Extract查询在SQL中运行正常,但它在activerecord的更新中无效。

2 个答案:

答案 0 :(得分:3)

很多时差的方法。您可以制作自定义时差方法,如:

 myApp.directive('googleplace', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, model) {
            var options = {
                types: [],
                componentRestrictions: {country: 'in'}
            };
            scope.gPlace = new google.maps.places.Autocomplete(element[0], options);

            google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
                scope.$apply(function() {
                    model.$setViewValue(element.val());                
                });
            });
        }
    };
});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.gPlace;
}

并使用它

def time_diff(start_time, end_time)
  seconds_diff = (start_time - end_time).to_i.abs

  hours = seconds_diff / 3600
  seconds_diff -= hours * 3600

  minutes = seconds_diff / 60
  seconds_diff -= minutes * 60

  seconds = seconds_diff

  "#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end

或者您可以使用ruby gem time_difference

答案 1 :(得分:2)

extract (epoch ...)给出一个以秒为单位的间隔,因此请使用:

select extract (
    epoch from now() - '2015-09-14 03:06:02.848+02'::timestamp)::int/60 
    as minutes;

 minutes
---------
       7
(1 row)