:如rails routes.rb

rya*_*ogo 58 ruby routing ruby-on-rails ruby-on-rails-3

config/routes.rb,我尝试了两个:

root :to => 'things#index', :as => 'things'
Run Code Online (Sandbox Code Playgroud)

root :to => 'things#index'
Run Code Online (Sandbox Code Playgroud)

当我击中时http://localhost:3000/,两种方法都有效,似乎没有什么不同.

:as用于什么选项?

And*_*man 88

:as选项形成一个命名路由.

通常它用于非根路由.例如:

match '/search' => 'search#search', :as => 'search' # SearchController#search
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

<%= link_to search_path, 'Click Here to Search!' %>
Run Code Online (Sandbox Code Playgroud)

search_path并且search_url因为而定义:as

对于根的路线,你真的不需要:as,因为该网址助手root_path,并root_url通过Rails的为您所定义.


Rom*_*cha 15

Rails 4兼容.

path_to_your_app/config/routes.rb

get "/profile/edit" => "users#profile_edit", :as => "edit_me"
Run Code Online (Sandbox Code Playgroud)

从ruby 2.0开始,您可以使用:

get "/profile/edit", to: "users#profile_edit", as: "edit_me"
Run Code Online (Sandbox Code Playgroud)

path_to_your_app/app/views/**in必要的视图中

<%= link_to "Edit profile", edit_me_path %>
Run Code Online (Sandbox Code Playgroud)

match如果您不确定是否需要,请不要使用:

在下一个模式中使用它时会产生漏洞:

match ':controller/:action/:id'
Run Code Online (Sandbox Code Playgroud)

来自文档:

如果match不指定HTTP方法,则不应在路由器中使用该方法.如果要将操作公开给GET和POST,请添加via:[:get, :post]选项.如果要将操作公开给GET,请在路由器中使用get:

代替: match "controller#action"

做: get "controller#action"

了解更多:

关于比赛

http://github.com/rails/rails/issues/5964

关于路线映射

http://apidock.com/rails/v4.0.2/ActionDispatch/Routing/Mapper/Base/match

http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html

关于路线一般

http://api.rubyonrails.org/classes/ActionDispatch/Routing.html


Dav*_*ulc 5

:as选项将创建一个命名路径。然后,您可以在控制器和视图中调用此路径(例如redirect_to things_path)。这对于根路径不是很有用(因为它已经命名为root),但是对于您添加的新路由却非常有用。