1

有没有办法确保该*_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]+\/.+/到我的资源路由的末尾,这可以使用 a/但因为它只使用正则表达式我无法:cat从 URL 获取参数

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

4

1 回答 1

0

我认为您正在以to_param不应该使用的方式使用它。如果您有一个to_param方法,那么还应该有一个from_param方法作为查找器,并且它应该始终映射到令牌而不是路径。所以 ie"#{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

于 2012-01-20T13:48:32.087 回答