Rails路由

Rails中文官网地址
Rails官网地址

  1. Rails收到请求:GET /patients/17
    查询路由,找到controller的action: get ‘/patient/:id’,to: ‘patients#show’
  2. 生成路径和URL地址
    route.rb :get ‘/patient/:id’,to: ‘patients#show’,as: ‘patient1’
    model: Patient
    Controller(patient_controller.rb): @patient1=Patient.find(params[:id])
    View(patient/show.html.erb): <%= link_to ‘Patient Record’,Patient_path(@patient1)%>
    (patient_path: Patient-model)
  3. 资源路由resource:Rails的默认风格,声明所有常用动作
    1
    2
    3
    4
    5
    6
    e.g :photos(复数资源)
    生成路径和URL的辅助方法:
    (1)photos_path 返回/photos
    (2)new_photo_path 返回/photos/new
    (3)edit_photo_path(:id) 返回/photos/:id/edit
    (4)photo_path(:id) 返回/photos/:id
1
2
3
4
5
e.g :geocoder(单数资源)映射到Geocoders控制器动作上
生成路径和URL的辅助方法:
(1)geocoder_path 返回/geocoder
(2)new_geocoder_path 返回/geocoder/new
(3)edit_geocoder_path 返回/geocoder/edit
  1. 指定action和controller
    get ‘profile’,to: ‘users#show’
    get ‘profile’,to: :show, controller: ‘users’
  2. 指定命名空间controller/admin/articles_controller.rb指定命名空间为Admin
    Controller: class Admin::ArticlesController
    route.rb :(1) /admin/articles/new
    1
    2
    3
    namespace :admin do
    resourcs :articles
    end

(2)/articles映射到Admin::Articles

1
2
3
scope module: 'admin' do
resources :articles
end

(3)/admin/articles映射到Articles

1
2
3
scope '/admin' do
resources :articles
end

  1. 嵌套资源