Rails 相對較新,因此無法解決此問題。
當前有一個路由:/test/testing/:id
一旦用戶點擊該路由,它將在資料庫中找到一個具有該特定 id 的專案并將 URL 設定為localhost:3000/test/testing/1-name-of-this-item
但是,如果您只是手動輸入該 URL,例如:localhost:3000/test/testing/1,/test/testing/1-name-of-this-item如果有某種方法可以在頁面加載之前更改引數,我希望它要么重定向到OR。但不完全確定如何做到這一點。
感謝您的幫助!
uj5u.com熱心網友回復:
您可以嘗試兩種方法來處理此問題
1:使用以下 Gem,它將根據您想要的屬性構建 URL https://github.com/norman/friendly_id
2:覆寫模型中的 to_param 方法并傳遞您希望在 URL 路徑中顯示的屬性
https://apidock.com/rails/ActiveRecord/Base/to_param
uj5u.com熱心網友回復:
根據您上面的評論,我假設您有一個Testing模型,其中至少有一個名為 columnid和 column path。因為您沒有提到路徑是如何生成的,所以我將假設該列已預先填充并回傳類似 slug 的內容,1-name-of-this-item并且路徑前綴的數字始終與記錄的 ID 同步。
此外,我猜你已經正確設定了路由,這/test是一個命名空間,/testing并被定義為一個普通的resources :testing. 這讓我假設 path_helpertest_testing_path是由 Rails 生成的。
如果是這種情況,那么只需將show控制器方法更改為:
def show
@testing = Testing.find(params[:id])
if @testing.path != params[:id]
redirect_to test_testing_path(@testing.path)
else
respond_to do |format|
format.html # show.html.erb
format.json { render json: @testing }
end
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364007.html
下一篇:自定義型別總是改變記錄,讓它變臟
