拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Rails5-如何在子档案夹中设定控制器?

Rails5-如何在子档案夹中设定控制器?

白鹭 - 2022-03-15 1972 0 0

api我的控制器档案有一个子档案夹。所以当我打电话时,POST "/api/auth"我希望程序使用 rails 约定到达那里。IE我不想为每个呼叫撰写路由,而是使用 rails“专利”,使 rails 转到 CRUD 操作,理解 PUT、POST、GET 本身。

所以在我的routes.rb我有:

  namespace :api do
    resources :debts, :auth
  end

但是当我发布(或获取)时,localhost:3000/api/auth我得到:

ActionController::RoutingError (uninitialized constant Api::AuthController)

我错过了什么?

请注意,我还需要在子档案夹中有许多控制器。match适合所有人的吗?

uj5u.com热心网友回复:

你也必须把你的控制器放在一个子档案夹中然后做例如

# /app/controllers/api/debts_controller.rb
module Api
  class DebtsController < ApiController
  end
end

# /app/controllers/api/auth_controller.rb
module Api
  class AuthController < ApiController
  end
end

然后在基本控制器档案夹中:

# /app/controllers/api_controller.rb
class ApiController < ApplicationController
end

uj5u.com热心网友回复:

您还需要命名该类才能使其正常作业。

可以使用以下2种方式:

module Api
  class AuthController < ApplicationController
    # Your controller code here
  end
end

class Api::AuthController < ApplicationController
  # Your controller code here
end

如果您有一些代码需要为 Api 命名空间内的每个控制器运行,您可以创建一个 Api 基本控制器,但这不是必需的。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *