Rails在没有使用ID的情况下将带有条的路由进行匹配 [英] Rails match routes with slugs without using ID in link
本文介绍了Rails在没有使用ID的情况下将带有条的路由进行匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的路线文件中,我可以轻松地将看起来像这样的匹配项放在一起,并且工作正常
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
此链接适用的链接是
link_to n.name, "/" + n.slug + "/" + n.id.to_s
我不想在URL中包含ID号,所以我希望这样做
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
但是问题在于,它没有为页面show controller提供ID。是否有某种方法可以使用:slug将其与数据库中的页面相匹配,以便找到:id,以便可以将:id传递给控制器?
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?
推荐答案
在您的路线中使用此
match "/:slug" => "pages#show"
然后在您的控制器中使用slug来找到该页面
And in your controller find the page by slug using this
@page = Page.find_by_slug(params[:slug])
这篇关于Rails在没有使用ID的情况下将带有条的路由进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文