“resources :post, except: :new” makes Rails think the route /posts/new would point to a post ID “new”

删除回忆录丶 提交于 2019-12-06 11:17:14

问题


I have the following route:

resources :success_criteria, except: :new

The following spec fails:

describe SuccessCriteriaController do
  describe 'routing' do
    it 'routes to #new' do
      expect(get('/success_criteria/new')).to_not be_routable
    end
  end
end

Failure message:

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"}

The controller looks like this:

class SuccessCriteriaController < InheritedResources::Base
  load_and_authorize_resource
end

Why does Rails think that posts/new would point to a post with the ID new? That's not right, is it? Does it maybe have to do with InheritedResources?


回答1:


I believe that if you don't add a constraint to your show route saying that it will only accept digits, everything you put after posts are mapped to be an id to that route.

That means that if your try to access posts/something it would probably throw an ActiveRecord error showing that it couldn't find the Post with id=something.

To add a constraint, add constraints like this:

resources :success_criteria, except: :new, constraints: { id: /\d+/ }


来源:https://stackoverflow.com/questions/31809636/resources-post-except-new-makes-rails-think-the-route-posts-new-would-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!