Rails路由學(xué)習(xí)
<%= link_to 'hello', {:controller => 'welcome', :action => 'say'} %>
會產(chǎn)生以下的鏈接(其他URL參數(shù)也可以在這穿,從第三個參數(shù)起,傳遞的都是a標(biāo)簽的屬性)
<a href="/welcome/say">hello</a>
match '/:controller/:action/:id.:format'
:id會轉(zhuǎn)為params[:id]傳到controller中去
.format讓路由接受.json、.xml等形式跺嗽,并且轉(zhuǎn)成params[:format]參數(shù)
寫作:
match '/meetings/:id' => 'events#show'
代表指向events controller的show方法
命名路由
match '/meetings' => 'events#index', :as=>"meetings"
自動生成meetings_path和meeting_url的Helper
設(shè)置首頁
root :to => 'welcome#show'
記得要刪除public/index.html這個文件
get 'account/overview' => 'account#overview'
限定條件
限定id為整數(shù)
match "events/show/:id" => "events#show", :constraints => {:id => /\d/}
限制ip
constrains(:ip=>/(127.0.0.1$)|(192.168.[0-9]{1,3}.[0-9]{1,3})$/) do
match '/events/show/:id' => "events#show"
end
Restful路由
resources :events do
resources :tasks, :people
end
自定義群集路由
resources :products do
collection do
products_controller.rb有個sold和on_offer方法
get :sold
post :on_offer
end
end
Namespace 使用
controller文件夾下有一個文件夾admin
namespace :admin do
admin文件夾下有個文件projects_controller.rb文件
resources :projects
end
URL_Helper變?yōu)閍dmin_projects_path
admin/projects/
###Request使用
在controller中直接使用
request.action_name
request.cookies
request.headers
request.params
request.xhr? #是不是Ajax請求
request.host_with_port
request.remote_ip
request.headers
request.session