Rails路由種類 (一般路由,命名路由)
使用 :except排除某個路由
resource :posts, :except => :show
可以添加額外一般路由 :to (不同的請求方法有區(qū)分 get,post)
get 'posts/:id', :to => 'post#show'
post 'posts/:id', :to => 'post#show'
命名路由: 添加 :as => XXXXX
get 'posts/:id', :to => 'post#show' :as => 'post_show' #這樣生成的路由會自動生成路由路徑名稱 ex. post_show_path
view界面內(nèi)可以直接使用rails方法創(chuàng)建一個超鏈接
<%= link_to 'id為1的微博', {:controller => 'posts', :action => 'show', :id => 1} %> #這個方法為一般路由添加方法
<%= link_to 'id為1的微博',show_post_path(1) %> #這個方法為命名路由添加方法
Rails.application.routes.draw do
resources :posts do
# get 'recent', :on => :collection
collection do #集合路由
get 'recent'
get 'today'
end
# member do #成員路由
# get 'recent'
# end
end
root 'posts#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
資源路由 (rails中最常用的路由方式)
資源路由可渲染和不渲染視圖
資源路由創(chuàng)建:
- 在controller里面需要創(chuàng)建相應的方法
def recent
#具體函數(shù)寫法按需求
end
- 創(chuàng)建視圖文件 recent.html.erb (需要創(chuàng)建時, 視圖文件根據(jù)具體需求構(gòu)建)
- 在routes文件中添加路由 (擴展資源路由添加)
- 集合路由添加方式 (兩種寫法)
生成的路由信息 posts/recent
- 集合路由添加方式 (兩種寫法)
resources :posts do
get 'recent', :on => :collection
end
resources :posts do
collection do #集合路由 需要添加多個時 采用這種寫法
get 'recent'
get 'today'
end
end
- 成員路由添加 (生成的路由信息會附加路由的id ex. posts/:id/recent )
resources :posts do
collection do #集合路由
get 'recent'
get 'today'
end
member do #成員路由
get 'recent'
end
end
總結(jié):rails中資源路由是最常用的路由方式,可以使用集合路由或者成員路由為其添加路由方法