繁体   English   中英

:如rails routes.rb

[英]:as in rails routes.rb

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

root :to => 'things#index', :as => 'things'

root :to => 'things#index'

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

什么是:as选项?

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

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

match '/search' => 'search#search', :as => 'search' # SearchController#search

然后你可以这样做:

<%= link_to search_path, 'Click Here to Search!' %>

search_pathsearch_url的定义是因为:as

对于根路由,您实际上并不需要:as因为Rails为您定义了URL帮助程序root_pathroot_url

Rails 4兼容。

path_to_your_app/config/routes.rb

get "/profile/edit" => "users#profile_edit", :as => "edit_me"

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

get "/profile/edit", to: "users#profile_edit", as: "edit_me"

在所需视图中的path_to_your_app/app/views/**in

<%= link_to "Edit profile", edit_me_path %>

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

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

match ':controller/:action/:id'

来自文档:

如果不指定HTTP方法,则不应在路由器中使用match方法。 如果要将操作公开给GET和POST,请通过以下方式添加: [: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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM