在Rails中别名化命名空间路由

khe*_*lal 3 ruby routing namespaces ruby-on-rails

给出以下routes.rb文件:

# Add Admin section routes
 map.namespace :admin do |admin|
   admin.resources :admin_users
   admin.resources :admin_user_sessions, :as => :sessions
   admin.resources :dashboard

   # Authentication Elements
   admin.login '/login',  :controller => 'admin_user_sessions', :action => 'new'    
   admin.logout '/logout', :controller => 'admin_user_sessions', :action => 'destroy'

   # Default is login page for admin_users
   admin.root :controller => 'admin_user_sessions', :action => 'new'
end
Run Code Online (Sandbox Code Playgroud)

是否可以将"admin"部分别名为别名,而无需更改应用程序中的每个重定向和link_to?主要原因是我希望能够在运行中配置它,并希望它也不易猜测.

Voy*_*yta 7

map.namespace方法只为其块内的路径设置一些常用选项.它使用with_options方法:

# File actionpack/lib/action_controller/routing/route_set.rb, line 47
        def namespace(name, options = {}, &block)
          if options[:namespace]
            with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block)
          else
            with_options({:path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block)
          end
        end
Run Code Online (Sandbox Code Playgroud)

因此可以with_options直接使用方法而不是namespace:

map.with_options(:path_prefix => "yournewprefix", :name_prefix => "admin_", :namespace => "admin/" ) do |admin|  
  admin.resources :admin_users
  # ....
end
Run Code Online (Sandbox Code Playgroud)

并且您可以像以前一样继续使用路由,但前缀将是"yournewprefix"而不是"admin"

admin_admin_users_path #=> /yournewprefix/admin_users
Run Code Online (Sandbox Code Playgroud)


小智 6

与任何其他资源一样,:path 似乎对我来说工作得很好。

namespace :admin, :path => "myspace" do
  resources : notice 
    resources :article do 
      resources :links , :path => "url"
    end 
  end
end
Run Code Online (Sandbox Code Playgroud)


oro*_*emo 5

为了创建命名空间的别名(api_version例如,从另一个路由器地址调用一个),您可以执行以下操作:

#routes.rb
%w(v1 v2).each do |api_version|
  namespace api_version, api_version: api_version, module: :v1 do
    resources :some_resource
    #...
  end
end
Run Code Online (Sandbox Code Playgroud)

这将导致路线/v1/some_resource/v2/some_resource到达同一个控制器.然后你可以params[:api_version]用来获得你需要的改进并做出相应的反应.