"resources :post, except: :new" 使 Rails 认为路由 /posts/new 会指向 post ID "new"
"resources :post, except: :new" makes Rails think the route /posts/new would point to a post ID "new"
我有以下路线:
resources :success_criteria, except: :new
以下规范失败:
describe SuccessCriteriaController do
describe 'routing' do
it 'routes to #new' do
expect(get('/success_criteria/new')).to_not be_routable
end
end
end
失败信息:
Failure/Error: expect(get('/posts/new')).to_not be_routable
expected {:get=>"/posts/new"} not to be routable, but it routes to {:controller=>"posts", :action=>"show", :id=>"new"}
控制器看起来像这样:
class SuccessCriteriaController < InheritedResources::Base
load_and_authorize_resource
end
为什么 Rails 认为 posts/new
会指向 ID 为 new
的 post?那不对,是吗?它可能与 InheritedResources 有关吗?
我相信如果你不在你的 show
路由中添加一个约束,说它只接受数字,你放在 posts
之后的所有内容都会映射到一个 id
到那条路线。
这意味着如果您尝试访问 posts/something
,它可能会抛出一个 ActiveRecord
错误,表明它找不到 Post
和 id=something
。
要添加约束,请像这样添加 constraints
:
resources :success_criteria, except: :new, constraints: { id: /\d+/ }
我有以下路线:
resources :success_criteria, except: :new
以下规范失败:
describe SuccessCriteriaController do
describe 'routing' do
it 'routes to #new' do
expect(get('/success_criteria/new')).to_not be_routable
end
end
end
失败信息:
Failure/Error: expect(get('/posts/new')).to_not be_routable
expected {:get=>"/posts/new"} not to be routable, but it routes to {:controller=>"posts", :action=>"show", :id=>"new"}
控制器看起来像这样:
class SuccessCriteriaController < InheritedResources::Base
load_and_authorize_resource
end
为什么 Rails 认为 posts/new
会指向 ID 为 new
的 post?那不对,是吗?它可能与 InheritedResources 有关吗?
我相信如果你不在你的 show
路由中添加一个约束,说它只接受数字,你放在 posts
之后的所有内容都会映射到一个 id
到那条路线。
这意味着如果您尝试访问 posts/something
,它可能会抛出一个 ActiveRecord
错误,表明它找不到 Post
和 id=something
。
要添加约束,请像这样添加 constraints
:
resources :success_criteria, except: :new, constraints: { id: /\d+/ }