Rails路由和控制器模块-namespacing?

Pål*_*Pål 4 ruby-on-rails

我无法为控制器创建模块,并使我的路由指向控制器内的该模块.

得到此错误:

Routing Error
uninitialized constant Api::Fb
Run Code Online (Sandbox Code Playgroud)

所以,这就是我的路线设置方式:

namespace :api do
  namespace :fb do
    post :login
    resources :my_lists do
      resources :my_wishes
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在我的fb_controller中,我想包含一些模块,它们会给我这样的路径:

/api/fb/my_lists
Run Code Online (Sandbox Code Playgroud)

这是我的一些fb_controller:

class Api::FbController < ApplicationController
  skip_before_filter :authenticate_user!, :only => [:login]

  include MyLists # <-- This is where i want to include the /my_lists
                  # namespace(currently not working, and gives me error 
                  # mentioned above)

  def login
    #loads of logic
  end
end
Run Code Online (Sandbox Code Playgroud)

MyLists.rb文件(我在其中定义模块)与fb_controller.rb位于同一目录中.

如何让命名空间指向fb_controller内部的模块,比如/ api/fb/my_lists?

Leo*_*rea 10

您设置的命名空间正在查找看起来像这样的控制器类

class Api::Fb::MyListsController

如果你想拥有一个看起来像/api/fb/my_lists但你想仍然使用的路线,FbController而不是MyListsController你需要设置你的路线看起来像这样

namespace :api do
  scope "/fb" do
    resources :my_lists, :controller => 'fb'
  end
end
Run Code Online (Sandbox Code Playgroud)

在我看来,而不是MyLists在你的模块中包含一些FbController似乎有点尴尬.

我可能会做的是拥有一个FB带有通用FbController 的模块MyListsController < FbController.无论如何,这超出了你的问题的范围.

以上应该满足您的需求.

编辑

根据您的评论,以及我对您尝试做的事情的假设,这是一个小例子:

配置/ routes.rb中

namespace :api do
  scope "/fb" do
    post "login" => "fb#login"
    # some fb controller specific routes
    resources :my_lists
  end
end
Run Code Online (Sandbox Code Playgroud)

API/FB/fb_controller.rb

class Api::FbController < ApiController
  # some facebook specific logic like authorization and such.
  def login
  end
end
Run Code Online (Sandbox Code Playgroud)

API/FB/my_lists_controller.rb

class Api::MyListsController < Api::FbController
  def create
    # Here the controller should gather the parameters and call the model's create
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,如果您只想创建一个MyListObject,那么您可以直接对模型执行逻辑操作.另一方面,如果您想要处理更多逻辑,那么您希望将该逻辑放在一个服务对象中,该服务对象处理MyList及其关联的Wishes或您的MyList模型的创建.我可能会去服务对象.请注意,服务对象应该是类而不是模块.