How do I access the previous record in a rails block
So basically I need to return the value of the previous Point.
e.g. I'm on the third point. I need the point.kilometric_position of the second point.
Part of my controller action is pasted here. Thanks in advance!
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
@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
If you want to use a more ruby friendly method, use inject like this:
@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
Would this be alright, seems inefficient but it's all I can think of right now:
@previous_point = @points[@points.index(point)-1]
I might do
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
but your question is too vague - it doesn't specify what distance
is, why you only want points with kilometric_position
equalling nil to have their position calculated, and what the kilometric_position
of the first point
should be.
精彩评论