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

我的git: https://github.com/chentianwei411/embeddable_comments/tree/rescue_from


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。


rails g scaffold Episode name slug

在controller修改:

private

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

进入rails console ,增加2条记录:

Episode.create(name: "Star Wars", slug: "test-1")
Episode.create(name: "Lord of the Rings", slug: "test-2")

在浏览器地址栏输入了错误的网址episodes/text, (正确的是episodes/text-1或者text-2)

导致出现❌

在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:

输入:

  1. exception查看❌提示的类
  2. params[:id]查看参数是什么
  3. c退出。

在controller中添加ActiveRecord::Rescuable::ClassMethods#erescue_from方法

加一个block,用于执行拯救:

  • 第一行对参数params[:id]再次进行模糊的搜索,并把可能的记录存在@episodes集合内。
  • 第二行渲染/search/show模版,并写一些提示信息给用户阅读
  • 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 %>

进一步完善功能

# 把第一字符替换为空. \w指[a-zA-z0-9_]
params[:id].gsub(/^[\w-]/, '')
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

class EpisodesController < ApplicationController
include SearchFallback

rescue_from(*klasses, with:nil, &block)

营救Rescue在controller actions中产生raise的exceptions。

  • *klasses -一系列的exception classes 或者class names
  • with选项 -方法名或一个Proc对象。用于处理*klasses。
  • &block是可选的块。

无论是with,还是&block都接受一个参数exception.


(Go rails)使用Rescue_from(ActiveSupport:Rescuable::ClassMethods)来解决404(ActiveRecord::RecordNotFound)❌的更多相关文章

  1. rails中validates_confirmation_of验证方法无效的解决办法

    rails的model中提供了很多种自带的验证方法,validates_confirmation_of可以验证变量xxx和xxx_confirmation是否相等:这可以用于验证2遍输入的密码是否一致 ...

  2. rails数据库查询 N + 1 查询的解决办法

    schema.rb ActiveRecord::Schema.define(version: 20150203032005) do create_table "addresses" ...

  3. 3-30 flash(api),rescue_from(); logger简介

    ActionDispatch::Flash < Objec pass temporary primitive-types (String, Array, Hash) between action ...

  4. 有意练习--Rails RESTful(一)

    书要反复提及<哪里有天才>在说,大多数所谓的天才是通过反复刻意练习获得. 当你的练习时间达到10000几个小时后,.你将成为该领域的专家. 近期在学习rails怎样实现RESTful We ...

  5. rails自定义出错页面

    一.出错类型 Exception ActionController::UnknownController, ActiveRecord::RecordNotFound ActionController: ...

  6. Mac上安装与更新Ruby,Rails运行环境

    Mac安装后就安装Xcode是个好主意,它将帮你安装好Unix环境需要的开发包,也可以独立安装command_line_tools_for_xcode 1.安装RVM RVM:Ruby Version ...

  7. Rails - ActiveRecord的where.not方法详解(copy)

    [说明:资料来自https://robots.thoughtbot.com/activerecords-wherenot] ActiveRecord's where.not Gabe Berke-Wi ...

  8. Ruby Rails学习中:注册表单,注册失败,注册成功

    接上篇 一. 注册表单 用户资料页面已经可以访问了, 但内容还不完整.下面我们要为网站创建一个注册表单. 1.使用 form_for 注册页面的核心是一个表单, 用于提交注册相关的信息(名字.电子邮件 ...

  9. Ruby Rails学习中:User 模型,验证用户数据

    用户建模 一. User 模型 实现用户注册功能的第一步是,创建一个数据结构,用于存取用户的信息. 在 Rails 中,数据模型的默认数据结构叫模型(model,MVC 中的 M).Rails 为解决 ...

随机推荐

  1. topcoder srm 465 div1

    problem1 link 以两个点$p,q$为中心的两个正方形的边长和最大为$2dist(p,q)$,即$p,q$距离的两倍. 也就是两个$p,q$的连线垂直穿过两个正方形的一对边且平分两个正方形. ...

  2. Linux电源管理(五)thermal【转】

    本文转载自:https://blog.csdn.net/zhouhuacai/article/details/78172267 版权声明:本文为博主原创文章,未经博主允许不得转载.    https: ...

  3. 关于link标签的用法, 不声明rel=stylesheet则无效? 在ff中必须声明rel属性!

    void 无效的, 空的; invalid: 无效的, void 和 invalid 在表示无效的时候, 是一样的, 等同的 the treaty (条约) was declared invalid ...

  4. 【原理、命令】Git基本原理、与Svn的区别、命令

    一.Git是什么? Git是目前世界上最先进的分布式版本控制系统.工作原理 / 流程:Workspace:工作区Index / Stage:暂存区Repository:仓库区(或本地仓库)Remote ...

  5. Centos 7 官网下载安装mysql server 5.6

    Centos 7 官网下载安装 mysql server # wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rp ...

  6. Vim的一些使用

    Vim的三种模式 normal(普通模式) insert(插入模式) command(命令模式) Vim的工作方式不同于常规的编辑器,在常规编辑器下对应到Vim中就是一直使用insert模式进行操作, ...

  7. Google advertiser api开发概述——批量处理

    批处理 大多数服务都提供同步 API,要求您发出请求然后等待响应,但 BatchJobService 允许您对多项服务执行批量操作,而无需等待操作完成. 与各服务的特定 mutate 操作不同,Bat ...

  8. Images之Dockerfiles

    Best practices for writing Dockerfiles This document covers recommended best practices and methods f ...

  9. EPPlus实战篇——Excel读取

    .net core 项目 可以从excel读取任何类型(T)的数据,只要T中的field的[Display(Name = "1233")]中的name==excel column ...

  10. Hadoop技术内幕1——源代码环境准备

    Hadoop核心 1.HDFS:高容错性.高伸缩性……,允许用户将Hadoop部署在廉价的硬件上,构建分布式系统 2.MapReduce:分布式计算框架,允许用户在不了解分布式系统底层细节的情况下,开 ...