(Go rails)使用Rescue_from(ActiveSupport:Rescuable::ClassMethods)来解决404(ActiveRecord::RecordNotFound)❌
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:
输入:
- exception查看❌提示的类
- params[:id]查看参数是什么
- 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)❌的更多相关文章
- rails中validates_confirmation_of验证方法无效的解决办法
rails的model中提供了很多种自带的验证方法,validates_confirmation_of可以验证变量xxx和xxx_confirmation是否相等:这可以用于验证2遍输入的密码是否一致 ...
- rails数据库查询 N + 1 查询的解决办法
schema.rb ActiveRecord::Schema.define(version: 20150203032005) do create_table "addresses" ...
- 3-30 flash(api),rescue_from(); logger简介
ActionDispatch::Flash < Objec pass temporary primitive-types (String, Array, Hash) between action ...
- 有意练习--Rails RESTful(一)
书要反复提及<哪里有天才>在说,大多数所谓的天才是通过反复刻意练习获得. 当你的练习时间达到10000几个小时后,.你将成为该领域的专家. 近期在学习rails怎样实现RESTful We ...
- rails自定义出错页面
一.出错类型 Exception ActionController::UnknownController, ActiveRecord::RecordNotFound ActionController: ...
- Mac上安装与更新Ruby,Rails运行环境
Mac安装后就安装Xcode是个好主意,它将帮你安装好Unix环境需要的开发包,也可以独立安装command_line_tools_for_xcode 1.安装RVM RVM:Ruby Version ...
- Rails - ActiveRecord的where.not方法详解(copy)
[说明:资料来自https://robots.thoughtbot.com/activerecords-wherenot] ActiveRecord's where.not Gabe Berke-Wi ...
- Ruby Rails学习中:注册表单,注册失败,注册成功
接上篇 一. 注册表单 用户资料页面已经可以访问了, 但内容还不完整.下面我们要为网站创建一个注册表单. 1.使用 form_for 注册页面的核心是一个表单, 用于提交注册相关的信息(名字.电子邮件 ...
- Ruby Rails学习中:User 模型,验证用户数据
用户建模 一. User 模型 实现用户注册功能的第一步是,创建一个数据结构,用于存取用户的信息. 在 Rails 中,数据模型的默认数据结构叫模型(model,MVC 中的 M).Rails 为解决 ...
随机推荐
- 写了个脚本将json换成md
用python 脚本将protocol.json中的json按照templete.md模版生成,结果在protocol.md中 Python: #!/usr/bin/python # -*- codi ...
- 如何在Framework中读取bundle中的Res
前因: 因为公司上架前后的原因,外围的平台层部分提前上线,而我做的功能部分需要晚一些上线,是单独的一个工程在其他仓库开发. 我的资源文件放在Bundle中.合到主工程中,资源文件不用改,直接拖进去.倒 ...
- Restful framework【第三篇】序列化组件
基本使用 -序列化 -对象,转成json格式 用drf的序列化组件 -定义一个类继承class BookSerializer(serializers.Serializer): -写字段,如果不指定so ...
- linux内核中侧async_tx是什么?
答: 异步内存传输api(asynchronous memory transfer/transform API),这是一种api,用来为应用提供操作DMA的API. 下图是async_tx在架构中所处 ...
- HDU 4366 Successor(dfs序 + 分块)题解
题意:每个人都有一个上司,每个人都有能力值和忠诚值,0是老板,现在给出m个询问,每次询问给出一个x,要求你找到x的所有直系和非直系下属中能力比他高的最忠诚的人是谁 思路:因为树上查询很麻烦,所以我们直 ...
- 【做题】atc_cf17-final_E - Combination Lock——巧妙转化及图论
题意:给出一个由26个小写字母组成的字符串,可以任意地进行若干个操作,每次操作是让指定区间内的字母变为下一个字母(z变成a).问是否存在方案使得这个字符串变为回文串. 一开始的想法是构造len/2条模 ...
- MySQL删除数据库时无响应解决办法
删除远程主机上MySQL中的一个数据库时,远程主机一直在响应,无法正常删除. 这个问题的解决办法如下:在远程主机上登录MySQL,执行show full processlist;观察state和inf ...
- 【ASP.NET】System.Web.Routing - HttpMethodConstraint Class
你可以自己定义你的ASP.NET程序接收的get post put 或者delete请求. 使用这个约束的方式为: void Application_Start(object sender, Even ...
- 【译】第45节---EF6-索引属性
原文:http://www.entityframeworktutorial.net/entityframework6/index-attribute-in-code-first.aspx Entity ...
- HDU 5236 Article(概率DP)
http://acm.hdu.edu.cn/showproblem.php?pid=5236 题意:现在有人要在文本编辑器中输入n个字符,然而这个编辑器有点问题. 在i+0.1s(i>=0)的时 ...