Rails路由出现在路由中但抛出404

我正在尝试向现有的控制器/操作添加一个简单的路由,但奇怪的是,即使路径似乎存在,我也会收到404错误。

这是我的routes.rb的相关部分:

  # Wines scope 'wine' do get '/', to: 'wines#index', as: 'wine_index' get '/:collection', to: 'wines#collection_detail', as: 'collection_detail' get '/:collection/:slug', to: 'wines#wine_detail', as: 'wine_detail' get '/:style', to: 'wines#style_detail', as: 'style_detail' end 

这似乎是正确的,因为这是我在检查时看到的内容:

 $ rake routes => Prefix Verb URI Pattern Controller#Action wine_index GET /wine(.:format) wines#index collection_detail GET /wine/:collection(.:format) wines#collection_detail wine_detail GET /wine/:collection/:slug(.:format) wines#wine_detail style_detail GET /wine/:style(.:format) wines#style_detail GET|POST /*path(.:format) pages#error404 

我还在控制台中看到了预期的响应:

 2.3.1 :003 > app.style_detail_path('semi-dry') => "/wine/semi-dry" 

然而,当我尝试访问/wine/semi-sweet/ (半甜是我用来搜索动作的样式“slug”)时,我收到404错误。

我能错过什么? 我在SO上搜索了几十个类似的问题,没有一个解决方案适用于我的情况。

看来你需要指定约束。 当你说’wines / semi-sweet’时,路由器将如何判断它是style_detail路径还是colletion_detail路径? 他们都有相同的面具’/ wines /:something’

它应该是这样的:

 scope 'wine' do get '/', to: 'wines#index', as: 'wine_index' get '/:style', to: 'wines#style_detail', as: 'style_detail', constraints: proc { |r| Style.include?(r.params[:style]) } get '/:collection', to: 'wines#collection_detail', as: 'collection_detail' get '/:collection/:slug', to: 'wines#wine_detail', as: 'wine_detail' end 

这样路由器将匹配具有葡萄酒样式的预定义单词(也可以是数组),所有其他字符串将被视为葡萄酒集合。

但最好更改这两条路径的掩码,以保证安全,例如:

  get '/:style', to: 'wines#style_detail', as: 'style_detail' get '/c/:collection', to: 'wines#collection_detail', as: 'collection_detail'