schadock schadock - 5 months ago 20
Ruby Question

Next item in collection/category

Hey I have museum app and there I have exhibits in categories.


type_id - is Category ID.

ex_id - is order of sightseeing - itn't primary key of exhibit


I have buttons to navigate to next and previous exhibit.

<% if @exhibit.previous %>
<%= link_to "", @exhibit.previous %>
<% end %>
<% if @exhibit.next %>
<%= link_to "", @exhibit.next %>
<% end %>


In model i have methods:

def next
Exhibit.order("ex_id").where("type_id <= ?", type_id).first
end

def previous
Exhibit.order("ex_id").where("type_id <= ?", type_id).last
end


I want navigate throught category order by ex id. My code did't work

Answer

Something like this should work for you

def next
  Exhibit.where("ex_id > ? AND type_id = ?", ex_id, type_id).first
end

def previous
  Exhibit.where("ex_id < ? AND type_id = ?", ex_id, type_id).last
end