Finding the previous / next item

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?

@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. :slight_smile:

HTH,

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. :slight_smile:

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.

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