【问题标题】:Rails url needing posts/:id/the-name-of-postRails url需要posts/:id/the-name-of-post
【发布时间】:2011-07-28 10:16:11
【问题描述】:

我希望我的 rails url 看起来像:

/posts/345/the-great-concept

当我在帖子模型中使用以下内容时,

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

在浏览器中鼠标悬停时,网址看起来很棒。并正常运行。但是,一旦页面加载到浏览器 url 中,它看起来像:

/posts/345%2Fthe-great-concept

需要明确的是,“名称”只是为了好看 - 帖子仅通过 id 检索。我也不想使用数据库 slug 方法。

我应该如何更好地解决这个问题?

ps。也不想要“/posts/345-the-great-concept”...

【问题讨论】:

    标签: ruby-on-rails url routes vanity-url


    【解决方案1】:

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

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

    edit:好的,斜线确实很重要;以下是解决方法:

    为此创建自定义路由:

    # 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
    

    然后将您的路线更改为显示操作,以便链接到花哨的 url:

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

    我创建了一个应用程序来测试所有这些,如果有兴趣,您可以在以下位置查看: https://github.com/unixmonkey/Pretty-Path

    【讨论】:

    • 谢谢,但我想弄清楚如何获取网址:/posts/345/the-great-concept 而不是 /posts/345-the-great-concept。后者我已经知道该怎么做了。
    • @dnewman 更新了我的答案。它更复杂,但符合您的规格。希望对您有所帮助!
    • 嘿伙计 - 我很感激帮助......是的,我希望不必从现有的 post_path(@post) 重写我的所有视图 link_to 路径。这是一个相当大的应用程序。正在寻找某种方式让应用程序忽略如下/posts/:id/*ignore/[更多内容]。我认为我需要深入挖掘路线。
    • 您实际上不必更改这些路线,但我认为您会想要保持一致性。您也许可以编写自己的 post_path 和 post_url 助手来自动找出 slug 部分: def post_url(post); slug_path(post, :slug => post.slug);结束
    猜你喜欢
    • 2023-02-09
    • 2022-12-02
    • 2022-12-02
    • 2020-12-19
    • 2022-12-01
    • 1970-01-01
    • 2021-01-29
    • 2020-08-25
    • 2022-12-28
    相关资源
    最近更新 更多