Rails match routes with slugs without using ID in link

白昼怎懂夜的黑 提交于 2019-12-10 17:53:57

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/11355220/rails-match-routes-with-slugs-without-using-id-in-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!