title: Rails best way to get previous and next active record object
body: <p>I need to get the previous and next active record objects with Rails. I did it, but don't know if it's the right way to do that.</p>
  
  <p>What I've got:</p>
  
  <p>Controller:</p>
  
  <pre><code>@product = Product.friendly.find(params[:id])
  
  order_list = Product.select(:id).all.map(&amp;:id)
  
  current_position = order_list.index(@product.id)
  
  @previous_product = @collection.products.find(order_list[current_position - 1]) if order_list[current_position - 1]
  @next_product = @collection.products.find(order_list[current_position + 1]) if order_list[current_position + 1]
  
  @previous_product ||= Product.last
  @next_product ||= Product.first
  </code></pre>
  
  <p>product_model.rb</p>
  
  <pre><code>default_scope -&gt; {order(:product_sub_group_id =&gt; :asc, :id =&gt; :asc)}
  </code></pre>
  
  <p>So, the problem here is that I need to go to my database and get all this ids to know who is the previous and the next.</p>
  
  <p>Tried to use the gem <a href="https://github.com/glebm/order_query">order_query</a>, but it did not work for me and I noted that it goes to the database and fetch all the records in that order, so, that's why I did the same but getting only the ids.</p>
  
  <p>All the solutions that I found was with simple order querys. Order by id or something like a priority field.</p>