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. Failed to set session cookie. Maybe you are using HTTP instead of HTTPS to access phpMyAdmin.

    原因:使用负载均衡的时候,第一次请求phpMyAdmin主页的时候web01进行处理,页面返回的cookie存放在web01上.填写用户名密码提交之后,是web02进行处理的,此时给页面的cookie ...

  2. ODAC(V9.5.15) 学习笔记(一)总论

    一直在使用ODAC做开发,没时间仔细研究一下,目前采用的是3层结构,ODAC+TDataSetProvider+TClientDataSet做数据处理,也没有多大问题.下一步要开发B/S的程序了,打算 ...

  3. Python3基础 dict 推导式 生成10以内+奇数的值为True 偶数为False的字典

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  4. P4556 [Vani有约会]雨天的尾巴

    目录 思路 优化 过程中的问题/疑问 错误 代码 思路 每个节点维护一课线段树(当然是动态开点) 线段树的作用是统计这个节点有多少种粮食型号,以及最多的粮食型号 然后树上差分,u和v点 +1,lca( ...

  5. 怎么在父窗口调用它页面的iframe里面数据,进行操作?

    注:在服务器下操作有效果,本地无效 document.getElementById("taskdetail1").contentWindow.test(a) document.ge ...

  6. WEB 安全学习 一、mysql 注入漏洞

    转载: https://www.cnblogs.com/cui0x01/p/8620524.html 一.Mysql数据库结构 数据库A 表名 列名 数据 数据库B 表名 列名 数据 Mysql5.0 ...

  7. 七、面向对象编程(OOP)

    面向对象编程:一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. 1.类(class) class:自定义的对象数据类型.基于类创建多个对象,每个对象具备类的通用行 ...

  8. 微信小游戏开发之JS面向对象

    //游戏开发之面向对象 //在js的开发模式中有两种模式:函数式+面向对象 //1.es5 // 拓展一:函数的申明和表达式之间的区别 // 函数的申明: // function funA(){ // ...

  9. 【BZOJ】3139: [Hnoi2013]比赛

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3139 可以发现,答案之和得分的序列有关,而且和序列中每个元素的顺序无关.考虑HASH所有的 ...

  10. SPOJ QTREE Query on a tree 树链剖分+线段树

    题目链接:http://www.spoj.com/problems/QTREE/en/ QTREE - Query on a tree #tree You are given a tree (an a ...