redirect_to後面用_path或_url的時機應該怎麼判斷呢?
之前做rails 101的練習時,書中指示一開始先用scaffold產出程式,後面再以此為基礎進行修改。
在controller檔案中,原本剛產出的destroy部份程式碼寫的是
format.html { redirect_to(posts_url) }
用的是_url。
不過在下個部份實作 nested resources時,便被修改為
format.html { redirect_to(board_posts_path(@board,@post)) }
變成了_path。
試了一下,不管使用哪個都會動。
我知道用_path的是產生相對位置的連結,用_url會產生絕對位置的連結,
但不知道什麼時候要用哪一個比較好?
今天讀rails3 in action時,在controller destroy部份又提到:
Then it uses redirect_to to take you to the purchases_url, which is the router helper defined to take you to http://localhost:3000/purchases. Note that this action uses the purchases_url method rather than purchase_path, which generate a full URL back to the purchase listing, such as http://localhost:3000/purchases/1.
一副好像很有深意的樣子...
問題他說了要Note之後也沒說為什麼呀>"<
還請各位大神解惑,感激不盡。
一般來說在View的時候我們會用path,而在Controller的時候我們會用url。
因為在View的時候使用path連到我們自己domain底下的相對網址會比較節省時間也提昇些許效能,而url通常我們會使用在redirect_to的3xx轉向,這種情況就得使用絕對路徑因此我們會使用url,還有種情況你必須使用url,就是在有SSL的網址與沒有SSL的網址間互傳的時候,你必須使用絕對路徑,因此請使用url。
不過為了一些SEO的理由,使用絕對路徑會比使用相對路徑來的優秀,例如說root_url會比root_path來的好。
有錯請各位大神指正,謝謝。
http://gogojimmy.net/blog/2011/12/02/when-to-use-url-or-path-in-rails/
好帖我頂!
一般來說在View的時候我們會用path,而在Controller的時候我們會用path
這兩句是不是有其中一個要換成url呢?還是真的兩個都是path? 看不太懂 Orz
一般來說在View的時候我們會用path,而在Controller的時候我們會用url吧?
引 The Rails 3 Way p.47
"According to the HTTP spec, redirects should specify a URI, which can be interpreted(by some people) to mean a fully-qualified URL. Therefore, if you want to be pedantic about it, you probably should always use the _url version when you use a named route as an argument to redirect_to in your controller code."
真的打錯字了,改謝指正XD