Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails match routes with slugs without using ID in link

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?

like image 460
mediarts Avatar asked Feb 19 '23 22:02

mediarts


2 Answers

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])
like image 81
Chris Avatar answered Mar 04 '23 07:03

Chris


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
like image 44
Alexander Popov Avatar answered Mar 04 '23 07:03

Alexander Popov