如何访问rails块中的上一条记录

时间:2011-03-20 17:14:39

标签: ruby

所以基本上我需要返回前一个Point的值。

e.g。我在第三个​​点。我需要第二个点的point.kilometric_position。

我的部分控制器操作已粘贴在此处。提前谢谢!

def calculate
  @points = Point.all

  # loop through all the points
  @points.each do |point|
    # calculate the current kilometric position
    if point.kilometric_position.nil?
      # kilometric_position = previous_kilometric_position + distance
    end
  end
end

4 个答案:

答案 0 :(得分:4)

@points.each_with_index do |point, i|
  previous_point = @points[i-1] unless i==0

  next unless previous_point
  distance = point.distance_to(previous_point)
  # do something with distance
end

答案 1 :(得分:2)

如果你想使用更友好的ruby方法,请使用这样的注入:

@points.inject do |previous,current|
  previous  # first time through, this is the first value
  current   # first time through, this is the second value

  # do a bunch of stuff

  previous = current
end

答案 2 :(得分:0)

这会好吗,看起来效率低下但是现在我能想到的只有:

@previous_point = @points[@points.index(point)-1]

答案 3 :(得分:0)

我可能会这样做

def calculate
  # Why were you using @points rather than points?
  points = Point.all

  current_kilometric_position = 0
  # loop through all the points
  points.each do |point|
    point.kilometric_position = current_kilometric_position
    current_kilometric_position += distance
  end
end

但你的问题太模糊了 - 它没有指明distance是什么,为什么你只想要kilometric_position等于nil的点来计算他们的位置,以及kilometric_position是什么第一个point应该是。