【发布时间】: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 => /[0-9]+\/.+/ 添加到我的资源路由的末尾,这可以使用/,但因为它只使用正则表达式,所以我无法从 URL 获取:cat 参数
那么,有没有办法确保我的自定义路由被news_path 方法识别?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 rails-routing custom-routes