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.
-
Can you please provide some relevant code to get a clearer understanding of what you are trying to do? – Mark Merritt Mar 31 '19 at 21:15
-
Essentially I want to create these functions: <%= link_to nested-resource_path(nested-resource.id WHERE id = min) %> and <%= link_to nested-resource_path(nested-resource.id WHERE id = next-largest) %> but I am unsure if this is possible/what the syntax would be. Sorry if this is unclear, I don't know id there is any specific code that would be useful. – dsteinbr1 Mar 31 '19 at 21:50
1 Answers
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) %>

- 56
- 1
- 4
-
I like the way you are looking at this but I want to see if I can take it a step further. Instead of seeing a list of links, similar to an index using the "each" function, I want to condense the links into a single "Next" link that will automatically redirect the user to the next "Show" page in the sequence. Any ideas on this front? – dsteinbr1 Mar 31 '19 at 22:15
-
1Ah, I misread your question, my mistake. I've updated my answer with something that I think will work. Hopefully I've got the right idea this time. – Jonathan Thom Mar 31 '19 at 22:23