簡體   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