In my routes file I can easily put together a match that looks like this and works just fine
match '/:slug/:id' => "pages#show", :id => :id
the link in the view that this works for is
link_to n.name, "/" + n.slug + "/" + n.id.to_s
I'd rather not include the ID number in the URL so I was hoping to do something like
match '/:slug' => "pages#show", :slug => :slug
But the problem is this doesn't provide the id to the pages show controller. Is there some way of using the :slug to match it to the page in the database with this slug to find the :id so I can pass the :id to the controller?
In your routes use this
match "/:slug" => "pages#show"
And in your controller find the page by slug using this
@page = Page.find_by_slug(params[:slug])
You could also do this:
resources :pages, only: :show, param: :slug
which will generate
page GET /pages/:slug/(.:format) pages#show
I order to be able to use this helper like this: page_path(page)
, where page is an instance of Page
, you also need to override the to_param
method like so:
def to_param
slug
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With