Ruby-on-rails Rails 控制器命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22913318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Controller Namespace
提问by kashif
What are advantages and disadvantages of using namespace in ruby on rails. For example: I've many controllers like
在 ruby on rails 中使用命名空间的优缺点是什么。例如:我有很多控制器喜欢
CompanyLocations
CompanyXXXX
CompanySports
CompanyActivites
CompanyQQQQQ
I want to put all these controllers in Company folder. What is the rails best practice for this ?
我想把所有这些控制器放在公司文件夹中。为此,rails 的最佳实践是什么?
回答by Jenorish
You have to create a subfolder inside your controller/ directory, and the same in your views/ directory.
你必须在你的控制器/目录中创建一个子文件夹,在你的视图/目录中也是如此。
Your controller file should look like
你的控制器文件应该看起来像
module Company
class SportsController < ApplicationController
def index
end
end
end
...or
...或者
class Company::SportsController < ApplicationController
def index
end
end
You can also call your partials this way
你也可以这样调用你的partials
render :template => "company/sports/index"
Then in routes.rb
然后在routes.rb
namespace :company do
resources :sports
end
回答by Зелёный
Just pull your controllers in the folder.
create folder app/controllers/company
and create a controller locations_controller.rbwith structure:
只需将您的控制器拉到文件夹中即可。
创建文件夹app/controllers/company
并创建一个locations_controller.rb具有结构的控制器:
module Company
class LocationsController < ApplicationController
layout '/path/to/layout'
append_view_path 'app/views/path/to/views'
def index
end
end
end
in routes.rbuse scope :module:
在routes.rb使用scope :module:
scope module: 'company' do
get '/locations', to: 'locations#index' # this route in scope
end
this generate routes:
这会生成路线:
locations_path GET /locations(.:format) company/locations#index
update:
更新:
Just tips. For views and layout you can use: ActionController#layoutand ActionController#append_view_path.
只是提示。对于视图和布局,您可以使用: ActionController#layout和ActionController#append_view_path。

