给出以下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
是否可以将'admin'部分别名为别名,而无需更改应用程序中的每个重定向和link_to?主要原因是我希望可以随时配置它,并希望它也不易猜测。
答案 0 :(得分: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
因此可以直接使用with_options
方法代替namespace
:
map.with_options(:path_prefix => "yournewprefix", :name_prefix => "admin_", :namespace => "admin/" ) do |admin|
admin.resources :admin_users
# ....
end
您可以继续使用与之前相同的路线,但前缀将是“yournewprefix”而不是“admin”
admin_admin_users_path #=> /yournewprefix/admin_users
答案 1 :(得分: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
这将导致路由/v1/some_resource
和/v2/some_resource
到达同一个控制器。然后你可以使用params[:api_version]
获得你需要的改进并做出相应的反应。
答案 2 :(得分:3)
与任何其他资源一样,:路径似乎对我来说很好。
namespace :admin, :path => "myspace" do
resources : notice
resources :article do
resources :links , :path => "url"
end
end
end