如果我有ID爲1的Post模型,了一個奇怪的關於ActiveRecord的.find(ID)方法
我可以通過訪問該資源
http://localhost:3000/posts/1
但weired的是,當我使用這些URL,我可以得到相同的結果。
http://localhost:3000/posts/1somethingweird-blah-blah-blah-idont-like-this
我該如何預防?
如果我有ID爲1的Post模型,了一個奇怪的關於ActiveRecord的.find(ID)方法
我可以通過訪問該資源
http://localhost:3000/posts/1
但weired的是,當我使用這些URL,我可以得到相同的結果。
http://localhost:3000/posts/1somethingweird-blah-blah-blah-idont-like-this
我該如何預防?
這可能是因爲params[:id]
正在從String
轉換爲int
和Ruby中調用"1somethingweird-blah-blah-blah-idont-like-this".to_i
實際上將導致1
。
您可以在路由層面解決這個問題:
resources :posts, :constraints => {:id => /[0-9]+/}
這是因爲.find本質上只是需要你傳遞什麼PARAM和做就可以了to_i,所以字符串''1somethingweird-等等,blah- blah-idont-like-this'.to_i'會返回1 – Magicmarkker