一般路由
get 'meetings/:id', :to => 'events#show'
post 'meetings', :to =>'events#create'
events_controller的show和create action
简写
get 'meetings/:id' => 'events#show'
其中:id会被转车一个参数params[:id]传到Controller里。
match路由
match ':controller(/:action(/:id(.:format)))', :via => :all
括号内的内容表示可有可无的内容
match '/:controller', via: :all
match '/:controller/:action', via: :all
match '/:controller/:action/:id', via: :all
match '/:controller.:format', via: :all
match '/:controller/:action.:format', via: :all
match '/:controller/:action/:id.:format', via: :all
match '/test_match/:action'=> 'test_match#:action' ,:via => :all
.format让路由可以接受.json、.xml参数,并且转成params[:format]参数中。
命名路由
get '/meetings' => 'events#index', :as => 'meetings'
其中的:as部分会产生meetings_path和meeting_url的Helpers,_path是相对路径,_url是绝对路径。
路由重定向
get '/foo' => redirect('/bar')
get "/ihower" => redirect("http://ihower.tw")
设置首页
root :to => 'welcome#show'
限定动词
match 'account/overview' => 'account#overview', :via=> :get
match 'account/setup' => 'account#setup', :via => [:get, :post]
match 'account/overview' => 'account#overview', :via => :all
scope规则
scope :controller => 'events', :path => '/foo', :as=>'bar' do
get 'meetings/:id' => :show, :as =>'meeting'
post 'meetings' => :create, :as=>'meerings'
end
产生bar_meeting_url和bar_meetings_url。
Namespace
namespace :admin do
resources :projects
end
controller对应Admin::ProjectsController,网址为/admin/projects,而URL Helper如admin_projects_path。
每个Namespace都可以设置首页
namespace :admin do
root 'projects#index'
end
这样连接/admin的时候就默认使用ProjectsController的index方法。
限定条件
限制:id是整数
match '/events/show/:id' => 'events#show', :constraints => {:id => /\d/}
甚至可以限定IP位置
constraints(:ip => /(^127.0.0.1$)|(^192.168.[0-9]{1,3}.[0-9]{1,3}$)/) do
match "/events/show/:id" => "events#show"
end
自定义集合路由
resources :products do
collection do
get :sold
post :on_offer
end
end
产生sold_products_path和on_offer_products_path这两个URL Helper,产生出如products/sold和products/on_off
限定路由
resources :events, :except => [:index, :show]
resources :events, :only => :create