删除PostgreSQL中的DB条目似乎进入了无限循环

时间:2013-06-17 21:41:00

标签: ruby-on-rails ruby postgresql

我正在使用GPS录制曲目并将其发送到我的Postgre数据库,然后我想删除速度= 0的前导和尾随测量。我试过这样:

while track.measurements.last.speed == 0
      track.measurements.last.destroy
end

(track.measurements.first相同)。当执行这段代码时,所有内容都会停止而没有任何错误。通过调试和逐步进行我发现的是它在这两行之间反复切换:

(rdb:102)s /var/lib/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/associations.rb:156 association = association_instance_get(name)

(rdb:102) l
[151, 160] in /var/lib/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/associations.rb
   151      # :nodoc:
   152      attr_reader :association_cache
   153  
   154      # Returns the association instance for the given name, instantiating it if it doesn't already exist
   155      def association(name) #:nodoc:
=> 156        association = association_instance_get(name)
   157  
   158        if association.nil?
   159          reflection  = self.class.reflect_on_association(name)
   160          association = reflection.association_class.new(self, reflection)
(rdb:102) s
/var/lib/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/associations.rb:170
@association_cache[name.to_sym]

(rdb:102) l
[165, 174] in /var/lib/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/associations.rb
   165      end
   166  
   167      private
   168        # Returns the specified association instance if it responds to :loaded?, nil otherwise.
   169        def association_instance_get(name)
=> 170          @association_cache[name.to_sym]
   171        end
   172  
   173        # Set the specified association instance.
   174        def association_instance_set(name, association)

可悲的是,这对我来说毫无意义。任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我猜测每个循环都不会查询track.measurements.last,所以你的代码是一个无限循环:

while true
track.measurements.last.destroy
end

你可以做一些变化,但效率不高:

last_is_zero = true
while last_is_zero 
  if track.measurements.last.speed == 0
    track.measurements.last.destroy
  else
    last_is_zero = false
  end
end

答案 1 :(得分:0)

嗯,不知怎的,这似乎干扰了一些关联,我不知道为什么这不起作用,但这是我的解决方案现在有效:

    #remove standing time from beginning and end
    for i in 0..self.measurements.length-1
      if self.measurements[i].speed == 0
        self.measurements[i].destroy
      else
        break
      end
    end

    for i in (self.measurements.length-1).downto(0)
      if self.measurements[i].speed == 0
        self.measurements[i].destroy
      else
        break
      end
    end

感谢您的帮助!