【问题标题】:Reducing redundancy in Rails routes and url helper减少 Rails 路由和 url 助手中的冗余
【发布时间】:2011-01-27 13:22:52
【问题描述】:

我想将文章的标题添加到其 url,类似于 SO URL。有人建议我在answer 中使用以下设置来回答我的另一个问题

# routes.rb
match '/articles/:id/:title' => 'articles#show', :as => :article_with_title

# articles/index.html.erb
link_to  article.title, article_with_title_path(article, :title => article.title.downcase.gsub(/[^a-z0-9]+/,' ').strip.gsub(/\s+/,'-'))

它有效,但我觉得它有点多余。有没有办法让它变得更好?处理多条路由的额外通用方法怎么样?

match '/articles/:id/:title' => 'articles#show'
match '/users/:id/:name' => 'users#show'
etc.

备注:

  1. 目前以下路线工作正常:/article/:id/:action/article/:id/:title,条件是文章不能有标题edit, show, index, etc.
  2. 我认为这里不需要friendly_id,因为路由明确包含:id
  3. 正如我所见,SO 对问题/question/:id/:title/posts/:id/:action 和用户/users/:id/:name/users/:action/:id 使用不同的路由

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 seo routes helper


    【解决方案1】:

    只需在您的模型中覆盖to_param。内存中未经测试的示例:

    def to_param
      self.id + "-" + self.name.parameterize
    end
    

    这种方法意味着您不必更改路由器,也可以继续使用Model.find(params[:id])或类似的方式。

    基本上Railscast 在另一个答案中提到的功能,以及friendly_id 的核心功能也是如此。

    【讨论】:

      【解决方案2】:

      Ryan Bates 在 screencast 上使用模型的名称或任何其他属性在 url 中而不是 id 方面做得很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多