Rails Controller Namespace

佐手、 提交于 2019-11-30 06:21:04

问题


What are advantages and disadvantages of using namespace in ruby on rails. For example: I've many controllers like

CompanyLocations 
CompanyXXXX 
CompanySports 
CompanyActivites
CompanyQQQQQ

I want to put all these controllers in Company folder. What is the rails best practice for this ?


回答1:


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

render :template => "company/sports/index"

Then in routes.rb

namespace :company do
 resources :sports
end



回答2:


Just pull your controllers in the folder.
create folder app/controllers/company


and create a controller locations_controller.rb with structure:
module Company
  class LocationsController < ApplicationController
    layout '/path/to/layout'
    append_view_path 'app/views/path/to/views'

    def index
    end

  end
end

in routes.rb use 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#layout and ActionController#append_view_path.



来源:https://stackoverflow.com/questions/22913318/rails-controller-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!