Ruby on rails Rails route出现在routes中,但抛出404
我试图向现有的控制器/操作添加一个简单的路由,但奇怪的是,我得到了一个404错误,即使该路由似乎存在 这是我的Ruby on rails Rails route出现在routes中,但抛出404,ruby-on-rails,ruby,routing,ruby-on-rails-5,Ruby On Rails,Ruby,Routing,Ruby On Rails 5,我试图向现有的控制器/操作添加一个简单的路由,但奇怪的是,我得到了一个404错误,即使该路由似乎存在 这是我的路线的相关部分。rb: # Wines scope 'wine' do get '/', to: 'wines#index', as: 'wine_index' get '/:collection', to: 'wines#collection_detail', as: 'collectio
路线的相关部分。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/
(semi-sweet是一个样式“slug”,我在操作中使用它来搜索),我得到了一个404错误
我能错过什么?我在S.O.上搜索了几十个类似的问题,但没有一个解决方案适用于我的情况。您似乎需要指定约束条件。当你说“葡萄酒/半甜葡萄酒”时,路由器将如何决定它是一条风格细节路径还是一条收集细节路径?他们都有相同的面具“/酒/:某物” 应该是这样的:
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'
如果删除尾部斜杠会发生什么?@jvillian没有变化。还是请从你的终端发布错误。是的。我刚开始注意到这一点。我想知道为什么Rails没有像你尝试创建一个重复的路径名时那样警告我。路由器抛出了一个404,因为你首先有一个集合路径,所以它搜索一个名为“semi dry”的集合,而这个集合并不存在。但是简单地重新排列路线是没有帮助的,您需要指定约束或更改“掩码”权限。我明白了。我只是好奇,如果您尝试将两条路线命名为相同的东西(例如:
wine\u detail
和wine\u detail
),为什么rake routes
会抛出一个有用的错误,但它根本没有抱怨我的冲突路线(例如:/wine/:something
和/wine/:something
实际上是完全相同的东西)如果客户端希望URL是相同的,那么简单地向两个路由添加一个约束以便Rails知道哪个是哪个有问题吗?以下是对我有效的方法:约束:lambda{r}Style.where(slug:r.params[:style])。是否为空?