bourne
(bourne)
January 5, 2011, 1:28pm
1
Given one model with a more complex sort in it.
@products = Product.all
If I now have the ID of a product that is in @products - what is the best way to find the previous/next element (keeping the model sort in mind, e.g. the previous / next with respect to the custom sort, not with respect to the database)? Is there a better way than stepping through using .each?
hassan
(Hassan Schroeder)
January 5, 2011, 3:48pm
2
@products is just an Array; you should look through the doc to see
the methods available. You might find Array#index and Array#at of
interest.
HTH,
11155
(-- --)
January 7, 2011, 6:12am
3
Hassan Schroeder wrote in post #972525:
@products is just an Array; you should look through the doc to see
the methods available. You might find Array#index and Array#at of
interest.
In other words. A Ruby Array (@products.class => Array) is an ordered
list, as opposed to Hash or Set, which store unordered collections of
objects.
So if you order the records from a fetch such as:
@products = Product.order(:name)
The Array will maintain the objects in the order specified in the query.
And getting next or previous is just as Hassan explained:
product = @products.at (3)
next_product = product.index(@products.index (product) +1)
Note. Don't forget to check the array bounds or you might get unexpected
results.
bourne
(bourne)
January 7, 2011, 10:53pm
4
Thanks for the pointer to .at.
For the archives:
@product_before = 'tablehead'
@productindex = @products.index(@product)
if @productindex
if @productindex > 0
@product_before = 'product_' + @products.at(@productindex - 1).id.to_s
end
end