Rails路由:只做什么:[]在这里做什么?

时间:2015-02-14 18:07:15

标签: ruby-on-rails authentication devise url-routing

我看到一条Rails代码用于这样的路由:

namespace :my do
  resource :auth_states, only: [] do
    collection do
      get 'signed_in'
    end
  end


  resource :password, only: [:edit, :update]      
  # And all the actions a logged in user can perform under "my" namespace...
  # ...

end

据说此应用适用于devisecancancan gem。我想:auth_states部分在他/她可以执行以下所有操作之前验证用户是否已登录。但是我对only: []感到有些困惑。这是否表示不会为:auth_states生成任何操作?那个东西怎么样呢?这是否意味着没有访问者可以从外部访问auth_states,但应用程序本身仍然可以使用它? only: []是Rails中广泛使用的模式吗?

由于

2 个答案:

答案 0 :(得分:3)

only: []包含要为资源路由的白名单操作数组。例如,如果您指定

resource :auth_states, only: [:index]

然后只生成索引操作,因此

GET /auth_states

将起作用,而(新行动)

GET /auth_states/new

不会。传递空操作是将资源用作嵌套路由的命名空间的技巧。实际上,在您的情况下,路由器将路由

GET /auth_states/signed_in

但是,同时,不会路由

GET /auth_states
GET /auth_states/1234

有时,您会看到它与controller选项

结合使用
resource :authentication, controller: 'auth_states', only: [] do
  collection do
    get 'signed_in'
  end
end

生成

GET /authentication/signed_in

路由器有namespace方法,但它会自动将控制器范围限定为Ruby命名空间。使用这个技巧有时更有效,并且允许将属于同一个伞的路由分组,为它们添加相同的路径。

答案 1 :(得分:1)

:[]用作可选参数,以便您可以指定允许路由到特定控制器的特定操作 - auth_states。在您的情况下,似乎没有必要使用它。如果您指定某些操作仅说:[:index],那么索引操作将仅被路由而不会被路由。希望这能清除你的困惑。

相关问题