【问题标题】:"resources :post, except: :new" makes Rails think the route /posts/new would point to a post ID "new""resources :post, except: :new" 使 Rails 认为路由 /posts/new 将指向一个帖子 ID "new"
【发布时间】:2015-08-04 12:41:43
【问题描述】:

我有以下路线:

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 的帖子?这是不对的,是吗?它可能与 InheritedResources 有关吗?

【问题讨论】:

  • 也许你应该为单个资源声明路由? resource :success_criteria, except: :new
  • 我认为您对 InheritedResources 的关注是正确的。为什么帖子/新映射到“显示”操作?似乎存在潜在的误导。

标签: ruby-on-rails routing


【解决方案1】:

我相信,如果您不向您的 show 路由添加一个约束,说它只会接受数字,那么您在 posts 之后放置的所有内容都会映射为该路由的 id

这意味着如果您尝试访问posts/something,它可能会抛出ActiveRecord 错误,表明它无法找到Postid=something

要添加约束,请像这样添加constraints

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多