Search code examples
ruby-on-railsmethodshyperlinknested-resources

Creating link_to for sequential nested resources


I am creating a rails app whereby from a record's "show" page, the user is able to cycle through the record's nested resources (similar to a slideshow). For example, from the "show" page, the user will be able to link to the "show" for the first nested resource. From there, the user will be able to link to the "show" page of the next nested resource and so on. As the ids of each nested resource should be ordered smallest to largest, how can I create a link_to that looks for the next highest id (assuming nested resources are being created for multiple records simultaneously they may not necessarily be sequential) of a nested resource within a given record.


Solution

  • Because of Rails magic, you can pass the resource directly to the route helper, and it will use the correct id for that resource. For example:

    <% @foo.bars.each do |bar| %>
        <%= link_to bar.name, foo_bar_path(@foo, bar) %>
    <% end %>
    

    The above assumes that your route file looks something like:

    resources :foos do
        resources :bars
    end
    
    

    I highly recommend Rails Routing from the Outside In; it's been a very helpful resource for me!

    To set the order of the child resource, you could use a scope, like this:

    class Bar < ActiveRecord::Base
        scope :ordered, -> { order(id: :asc) }
    end
    
    

    And then in your view, call foo.bars.ordered.each do |bar| etc.... Your nested resource will be returned from lowest to highest ID, skipping over any that have been deleted.

    I hope this helps with what you were asking.

    EDIT

    I misread the question. To dynamically generate the "next" id, you could create method, next, on your child class. This answer seems to be something like what you want. Then in your view, you can just call:

    <%= link_to "Next", bar_path(current_bar.next) %>