rails-路由学习1
rails config/routes.rb 指定路由的代码如下
Rails4demo::Application.routes.draw do
root 'users#index'
resources :users
get 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }
get '/logout' => 'sessions#destroy', :as => :logout
get "/stories" => redirect("/photos")
end
上面的代码定义了5种风格的路由,rails在启动时会读取routes.rb,生成标准状态的格式,以此来匹配url,指定controller和action。
带defaults的get调用
Rails4demo::Application.routes.draw do
get '/logout' => 'sessions#destroy', :as => :logout
end
会生成以下变量
app: #<ActionDispatch::Routing::RouteSet::Dispatcher:0x007fd05e0cf7e8
@defaults={:format=>"jpg", :controller=>"photos", :action=>"show"},
@glob_param=nil,
@controller_class_names=#<ThreadSafe::Cache:0x007fd05e0cf7c0
@backend={},
@default_proc=nil>>
conditions: {:path_info=>"/photos/:id(.:format)", :required_defaults=>[:controller, :action], :request_method=>["GET"]}
requirements: {}
defaults: {:format=>"jpg", :controller=>"photos", :action=>"show"}
as: nil
anchor: true
指定了controller和action;如果url符合conditions的要求,app会执行。requirements 是一些其他限制。 ##带 as的get调用
Rails4demo::Application.routes.draw do
get '/logout' => 'sessions#destroy', :as => :logout
end
会生成以下变量
app: #<ActionDispatch::Routing::RouteSet::Dispatcher:0x007f8ded87e740
@defaults={:controller=>"sessions", :action=>"destroy"},
@glob_param=nil,
@controller_class_names=#<ThreadSafe::Cache:0x007f8ded87e718 @backend={},
@default_proc=nil>>
conditions: {:path_info=>"/logout(.:format)", :required_defaults=>[:controller, :action], :request_method=>["GET"]}
requirements: {}
defaults: {:controller=>"sessions", :action=>"destroy"}
as: "logout"
anchor: true
resources 会生成类似的8种app。 ActionDispatch::Routing::Mapper定义了 用于定义route的方法
module ActionDispatch
module Routing
class Mapper
include Base
include HttpHelpers
include Redirection
include Scoping
include Concerns
include Resources
end
end
end
- Base定义了 root, match 和 mount
- HttpHelper定义了get、put、patch、post、delete
- Scoping定了 scope、namespace、constraints
- Resources定义了resource、resources、collection、member、shallow 由url匹配到app是由journey执行的,这个gem主要是通过正则匹配,我们随后继续研究.