No typo. I didn’t call it id
because it’s not an ID. Seems confusing to me to call it that so I called it path
. But if you want to call the param id
you can do that:
get '*id', to: 'pages#show'
Now if you navigate to /my/cool/path
then param[:id]
will equal to /my/cool/path
.
If you want path helpers then just define them. In your routes.rb
file:
get '*path/images/:id', to: 'images#show', as: :page_image
get '*path', to: 'pages#show', as: :page
In your page.rb
file:
class Page < ApplicationRecord
...
def to_param
# ... return full path to page ...
end
end
With this in place if you want to link to a page in a view:
<%= link_to page.name, page_path(page) %>
If you want to redirect to a page in a controller:
redirect_to page_url(page)
With both of those I think you can just pass the raw “page” object in and it will assume the page
named route. If you want to show an image in a view:
<%= image_tag page_image_path(image, path: params[:path]) %>
That extra path
argument is a bit annoying. I think you can also use path params to get rid of that. Define your routes to instead be:
scope '*path' do
get 'images/:id', to: 'images#show', as: :page_image
end
get '*path', to: 'pages#show', as: :page
Then in your application_controller.rb
file define:
class ApplicationController < ActionController::Base
def default_url_options
{ path_params: { path: params[:path] } }
end
end
Now the current path
param will be automatically applied on the page_image
named route.
Disclaimer: None of the above is tested. Just is just off the top of my head. I’m sure there is a bug or two in there but the general idea should work. I highly recommend the Routing Guide as it goes over a lot of this stuff.