這次想試著讓它顯示我想要顯示的樣子
http://apidock.com/rails/ActiveSupport/Rescuable/ClassMethods/rescue_from
#ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
rescue_from ActiveRecord::RecordNotFound, with: :resource_not_found
protected
def resource_not_found
end
end
在ApplicationController加rescue_from,後面指定是哪一種錯誤的時候要用 因為這次是要修改ActiveRecord::RecordNotFound in ArticlesController#show這一種錯誤的行為,所以後面接的事ActiveRecord::RecordNotFound
resource_not_found留白是因為可能之後不同controller可能會想要有不一樣的動作,所以不在application controller裡面寫死,改寫在目標的controller裡面
#article.rb
protected
def resource_not_found
message = "The article you are looking for could not be found"
flash[:alert] = message
redirect_to root_path
end
這樣子如果在網址列輸入http://localhost:3000/articles/xxxx這種不存在的id的時候會改轉跳到root頁面,並且顯示flashWritten with StackEdit.
沒有留言:
張貼留言