[英]Ruby on Rails - Difference between redirect_to 'index' and redirect_to objects_path & redirect_to action: 'index'
我有一個簡單的模型和控制器。 讓我們以Kiwis為例:
def index
@kiwis = Kiwi.all
end
def destroy
kiwi = Kiwi.find(params[:id])
kiwi.destroy
redirect_to 'index'
end
我在索引頁面上使用了刪除鏈接。 當我使用redirect_to'index'時,頁面不會刷新模型。 我必須在頁面上進行一次硬刷新才能刪除獼猴桃。 但是,如果我使用redirect_to動作:“ index”或redirect_to kiwis_path,則該頁面將在destroy動作后更新。 我似乎找不到對此的解釋。 任何人都可以在這個問題上闡明一些想法。
在大多數情況下,建議使用命名的路由助手。 在您的情況下,正確的做法是redirect_to kiwis_path
。
當您調用redirect_to時,Rails將以302(重定向)狀態響應當前請求,然后客戶端(即您的瀏覽器)將向指定位置發出另一個請求 。 重定向的位置由傳遞給redirect_to
的參數確定。
當您將String
傳遞給redirect_to
它必須是URL(帶有協議和主機,例如“ http:// localhost:3000 / kiwis ”,或者不包含例如“ / kiwis”)
在您的情況下, redirect_to kiwis_path
是正確的。 它等效於redirect_to '/kiwis'
當您傳遞哈希參數action: 'index'
, url_for
方法用於生成URL。
redirect_to action: 'index'
與redirect_to url_for(action: 'index')
。 url_for(action: 'index')
將與/kiwis
路徑的路由匹配。
因此redirect_to action: 'index'
等同於redirect_to '/kiwis'
redirect_to kiwis_path
redirect_to '/kiwis'
和redirect_to kiwis_path
在這里,您可以了解redirect_to
接受的不同參數以及如何處理它們。
redirect_to 'index'
會發生什么? 我已經設置了一個測試控制器/動作來使用redirect_to 'index'
進行重定向。 讓我們看看使用curl發出請求時會發生什么。
~/projects/gitlab $ curl -v -H "Accept: text/html" http://localhost:3000/redirect_test
我省略了輸出中一些不相關的部分:
> GET /select_options HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.43.0
> Accept: text/html
>
< HTTP/1.1 302 Moved Temporarily
< X-Frame-Options: ALLOWALL
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< Location: http://localhost:3000index <----- That is not what we want!
您可以在顯示的最后一行上看到Location標頭的值不是所需的URL。 當我在Chrome中進行測試時,遇到此錯誤的重定向請求被取消。 因此,瀏覽器停留在同一頁面上並且沒有離開。 這可以解釋為什么您必須進行“硬刷新”才能看到頁面上的更改。
redirect_to 'index'
是無效的代碼。 您需要為redirect_to指定完整路徑。
您可能會將此與有效的render 'index'
混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.