Rails url 需要 posts/:id/the-name-of-post
我希望我的 Rails url 看起来像:
/posts/345/the-great-concept
当我在帖子模型中使用以下内容时,
def to_param
"#{id}/#{name.parameterize.downcase}"
end
将鼠标悬停在浏览器中时,网址看起来很棒。并正常运行。然而,一旦页面加载到浏览器 URL 中,它看起来像:
/posts/345%2Fthe-great-concept
需要明确的是,“名称”只是为了美观 - 该帖子仅通过 id 检索。我也不想使用数据库 slug 方法。
我应该如何更好地处理这个问题?
附注也不想要“/posts/345-the-great-concept”...
I would like my rails url to look like:
/posts/345/the-great-concept
when i use the following in my posts model,
def to_param
"#{id}/#{name.parameterize.downcase}"
end
the urls look great upon mousover in the browser. and function correctly. however, once the page is loaded in the browser url it looks like:
/posts/345%2Fthe-great-concept
and to be clear, the "name" is just for good looks - the post is retrieved only by id. also i do not want to use a database slug approach.
how should i better approach this?
ps. don't want "/posts/345-the-great-concept" either ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它被转义了,因为它不是路径的一部分,而是一个参数,所以它需要转义,否则你将使用错误的 uri。
编辑:好的,斜杠确实很重要;解决方法如下:
为此创建一个自定义路由:
然后创建您的 slug 方法:
然后将您的路由更改为显示操作,以便链接到精美的网址:
我创建了一个应用程序来测试所有这些,如果有兴趣,您可以检查一下:
https://github.com/unixmonkey/Pretty-Path
Its escaped because its not part of the path, but a param, so it needs to be escaped or you will be on the wrong uri.
edit: Okay, so the slash is indeed important; Here's how to tackle it:
Create a custom route for that:
Then create your slug method:
Then change your routes to the show action so the link to the fancy url:
I created an app to test all this out, if interested, you can check it out at:
https://github.com/unixmonkey/Pretty-Path