Rails maps routes to bullets without using an identifier in the link

In the routes file, I can easily put together a match that looks and works just fine

match '/:slug/:id' => "pages#show", :id => :id 

the link in the view it works for is

 link_to n.name, "/" + n.slug + "/" + n.id.to_s 

I would prefer not to include the id in the url, so I was hoping to do something like

 match '/:slug' => "pages#show", :slug => :slug 

But the problem is that this does not indicate the identifier on the show controller page. Is there a way to use: slug to map it to a page in the database with that slug to find: id so that I can pass: id to the controller?

+4
source share
3 answers

In your routes use this

 match "/:slug" => "pages#show" 

And in your controller, find the page using slug using this

 @page = Page.find_by_slug(params[:slug]) 
+6
source

Take a look at the https://github.com/norman/friendly_id gem, it greatly simplifies bullet routing.

+1
source

You can also do this:

 resources :pages, only: :show, param: :slug 

which will generate

GET page / pages /: slug / (.: format) page # show

I want to use this helper as follows: page_path(page) , where the page is an instance of Page , you also need to override the to_param method as follows:

 def to_param slug end 
+1
source

All Articles