Rails url 需要 posts/:id/the-name-of-post

发布于 2024-10-29 08:07:49 字数 442 浏览 2 评论 0原文

我希望我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘过的浮云 2024-11-05 08:07:49

它被转义了,因为它不是路径的一部分,而是一个参数,所以它需要转义,否则你将使用错误的 uri。

def to_param
  "#{id}-#{name.parameterize.downcase}"
end

编辑:好的,斜杠确实很重要;解决方法如下:

为此创建一个自定义路由:

# in config/routes.rb
resources :posts
match '/posts/:id/:slug' => 'posts#show', :as => :slug

然后创建您的 slug 方法:

# in app/models/post.rb
def slug
  title.parameterize.downcase
end

然后将您的路由更改为显示操作,以便链接到精美的网址:

# in any link to show; redirect after create, etc..
link_to slug_path(@post, :slug => @post.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.

def to_param
  "#{id}-#{name.parameterize.downcase}"
end

edit: Okay, so the slash is indeed important; Here's how to tackle it:

Create a custom route for that:

# in config/routes.rb
resources :posts
match '/posts/:id/:slug' => 'posts#show', :as => :slug

Then create your slug method:

# in app/models/post.rb
def slug
  title.parameterize.downcase
end

Then change your routes to the show action so the link to the fancy url:

# in any link to show; redirect after create, etc..
link_to slug_path(@post, :slug => @post.slug)

I created an app to test all this out, if interested, you can check it out at:
https://github.com/unixmonkey/Pretty-Path

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文