【问题标题】:Rails 3 custom route not recognized by *_path method*_path 方法无法识别 Rails 3 自定义路由
【发布时间】:2012-01-20 10:34:33
【问题描述】:

有没有办法确保*_path 方法识别自定义路由?

我有一个资源和一个到同一个控制器的自定义路由:

resources :news, :only => [:index, :show], :path => :nieuws
match '/nieuws/:cat/:id/:slug', :to => 'news#show'
match '/nieuws/:id/:slug', :to => 'news#show'

这工作正常,当请求http://www.example.com/nieuws/category/1/slug 时,它将显示正确的新闻项目。问题是我想使用news_path 方法链接到我的新闻项目。为了实现这一点,我在我的新闻项目模型中添加了以下代码:

def to_param
  if news_category
    "#{news_category.slug}/#{id}/#{slug}"
  else
    "#{id}/#{slug}"
  end
end

当不使用/ 来分隔cat、id 和slug 时,它可以正常工作,但是当使用/ 时,news_path 方法会失败并显示请求的页面:

No route matches {:action=>"show", :controller=>"news", :id=>#<NewsItem id: 1...etc

我的rake routes 输出:

news_index GET /nieuws(.:format)                {:action=>"index", :controller=>"news"}
news       GET /nieuws/:id(.:format)            {:action=>"show", :controller=>"news"}
               /nieuws/:cat/:id/:slug(.:format) {:controller=>"news", :action=>"show"}
               /nieuws/:id/:slug(.:format)      {:controller=>"news", :action=>"show"}

我已经尝试将, :id =&gt; /[0-9]+\/.+/ 添加到我的资源路由的末尾,这可以使用/,但因为它只使用正则表达式,所以我无法从 URL 获取:cat 参数

那么,有没有办法确保我的自定义路由被news_path 方法识别?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rails-routing custom-routes


    【解决方案1】:

    我认为您使用 to_param 的方式不应该使用它。如果你有一个to_param 方法,那么还应该有一个from_param 方法作为查找器,并且它应该始终映射到令牌而不是路径。所以即"#{news_category.slug}-#{id}-#{slug}" 而不是"#{news_category.slug}/#{id}/#{slug}"

    如果您不想按路径段分隔,则需要将其放入您的 news_path 调用中,如下所示:

    news_path(news, :cat => news_category.slug, :slug => slug)
    

    请参阅指南以获取更多建议:http://guides.rubyonrails.org/routing.html#segment-constraints

    【讨论】:

    • 感谢您的回答,但您给我的解决方案将生成一个类似于 www.example.com/nieuws/2?cat=category&amp;slug=slug 的链接。对于没有类别的项目,我想要实现的是 www.example.com/nieuws/category/2/slugwww.example.com/nieuws/2/slug。在仍然使用news_path 的同时是否有其他方法可以做到这一点,或者是在我的模型中创建我自己的 url/path 方法的唯一解决方案?
    • 您可以使用:as 选项创建命名路由,然后使用它们代替news_path 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 2015-01-15
    • 2018-07-06
    • 2017-05-01
    相关资源
    最近更新 更多