【问题标题】:Rails match routes with slugs without using ID in linkRails 将路线与 slug 匹配,而不在链接中使用 ID
【发布时间】:2012-07-06 12:00:30
【问题描述】:

在我的路由文件中,我可以轻松地将一个看起来像这样并且工作正常的匹配放在一起

match '/:slug/:id' => "pages#show", :id => :id

视图中适用的链接是

link_to n.name, "/" + n.slug + "/" + n.id.to_s

我不想在 URL 中包含 ID 号,所以我希望做类似的事情

match '/:slug' => "pages#show", :slug => :slug

但问题是这不会向页面显示控制器提供 id。是否有某种方法可以使用 :slug 将其与数据库中的页面相匹配,并使用该 slug 找到 :id 以便我可以将 :id 传递给控制器​​?

【问题讨论】:

    标签: ruby-on-rails-3 routes slug


    【解决方案1】:

    你也可以这样做:

    resources :pages, only: :show, param: :slug
    

    会生成

    页面 GET /pages/:slug/(.:format) pages#show

    我希望能够像这样使用这个助手:page_path(page),其中 page 是 Page 的一个实例,您还需要像这样覆盖 to_param 方法:

    def to_param
      slug
    end
    

    【讨论】:

      【解决方案2】:

      在你的路线中使用这个

      match "/:slug" => "pages#show"
      

      然后在你的控制器中使用这个通过 slug 找到页面

      @page = Page.find_by_slug(params[:slug])
      

      【讨论】:

        【解决方案3】:

        看看https://github.com/norman/friendly_id gem,它大大简化了使用 slug 的路由。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-12
          • 2020-05-17
          • 1970-01-01
          • 1970-01-01
          • 2021-04-18
          • 2017-07-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多