mediarts
mediarts

Reputation: 1521

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?

Upvotes: 4

Views: 4804

Answers (3)

Alexander Popov
Alexander Popov

Reputation: 24895

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

Upvotes: 2

Chris
Chris

Reputation: 111

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])

Upvotes: 6

binarycode
binarycode

Reputation: 1806

Take a look at https://github.com/norman/friendly_id gem, it simplifies routing with slugs a lot.

Upvotes: 1

Related Questions