(Go rails)使用Rescue_from来更好的解决404❌

https://gorails.com/episodes/handle-404-using-rescue_from?autoplay=1

Handle 404s Better Using Rescue_from

在controller层添加resuce_from方法。对ActiveRecord::RecordNotFound❌进行营救。

当用户拷贝链接错误或者其他导致错误的url,网页会弹出一个404.

Well, if we couldn't find the episode, or the forum thread or whatever they were looking for, if we can't find it directly with the perfect match, then we should take that and search the database and clean it up a little bit, but then go search the database。


class Episode < ApplicationRecord
  def to_param
    slug
  end
end

在controller中:

private

  def set_episode
    //find_by! 如果没有找到匹配的记录会raise an ActiveRecord::RecordNotFound
    @episode = Episode.find_by!(slug: params[id])
  end

  def episode_params
    params.require(:episode).permit(:name, :slug)
  end

输入了错误的网址episodes/text, (正确的是episodes/text-1)

导致出现❌

在controller:

class EpisodesController <ApplicationController
  before_action :set_episode, only: [:show, :edit, :update, :destroy]

  rescue_from ActiveRecord::RecordNotFound do |exception|
    byebug   //一个用于debug的gem中的方法,rails默认添加的 
  end
end

再刷新错误网页,然后看terminal的fservent_watch:

输入:

class EpisodesController <ApplicationController
  before_action :set_episode, only: [:show, :edit, :update, :destroy]

  rescue_from ActiveRecord::RecordNotFound do |exception|
     @episodes = Episode.where("slug LIKE ?", "%#{params[:id]}%")
     render "/search/show"
  end
end

新增一个views/search/show.html.erb

<h3>很抱歉,您要访问的页面不存在!</h3>
<% if @episodes.any? %>   <p>这里有一些相似的结果:</p>   <% @episodes.each do |episode| %>    <div>    <%= link_to episode.name, episode %>    </div>   <% end %>
<% else %>
<%= link_to "Check out all our episodes", episodes_path %>
<% end %>

 

进一步完善功能:加上 

class EpisodesController <ApplicationController
  before_action :set_episode, only: [:show, :edit, :update, :destroy]

  rescue_from ActiveRecord::RecordNotFound do |exception|
     @query = params[:id].gsub(/^[\w-]/, '')
     @episodes = Episode.where("name LIKE ? OR slug LIKE ?", "%#{@query}%", "%#{@query}%")
     render "/search/show"
  end
end

可以把recue_from放到一个单独的模块SearchFallback中:

把这个模块放入app/controllers/concern/search_fallback.rb中:

module SearchFallback
//因为included方法是ActiveSupport::Concern模块中的方法,所以extend这个模块,就能用included了 extend ActiveSupport::Concern //当这个模块被类包含后,则: included do rescue_from ActiveRecord::RecordNotFound do
|exception|   @query = params[:id].gsub(/[^\w-]/, '')    @episodes = Episode.where("name LIKE ? OR slug LIKE ?", "%#{@query}%", "%#{@query}%")    @forum_threads = Episode.where("name LIKE ? OR slug LIKE ?", "%#{@query}%", "%#{@query}%")    render "/search/show" end end end

然后EpisodesController, include SearchFallback


猜你喜欢

转载自www.cnblogs.com/chentianwei/p/9824098.html