Rails Controller Namespace

前端 未结 2 589
逝去的感伤
逝去的感伤 2020-12-13 08:05

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

CompanyLocations 
CompanyXXXX 
CompanySp         


        
相关标签:
2条回答
  • 2020-12-13 08:37

    Just pull your controllers in the folder.
    create folder app/controllers/company
    enter image description here
    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.

    0 讨论(0)
  • 2020-12-13 08:46

    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
    
    0 讨论(0)
提交回复
热议问题