如何使这个动作抛出一个404? [英] How to make this action throw a 404?

查看:156
本文介绍了如何使这个动作抛出一个404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下操作:

def show
  @video = @commentable = @favoritable = Video.find_by_key(params[:key])

  Video.increment_counter(:views_count, @video.id)
end

但现在如果 find_by_key 没有找到记录,它会抛出一个 RuntimeError 调用的id为nil )。

But right now if find_by_key doesn't find a record, it throws a RuntimeError (Called id for nil).

那么如何才能得到这个动作来抛出一个404如果没有找到记录?

So how can I get that action to throw a 404 if a record isn't found?

我正在运行Rails 3.2.1。

I'm running Rails 3.2.1.

推荐答案

在尝试使用 @ video.id 的值递增之前添加此项。

Add this before you try to increment using the value of @video.id.

raise ActiveRecord :: RecordNotFound if @ video.blank?

或使用b $版本的 find_by_key 如果没有找到,将会提高 ActiveRecord :: RecordNotFound

Or use the bang version of find_by_key which will raise ActiveRecord::RecordNotFound if it isn't found.

Video.find_by_key!(params [:key])

这篇关于如何使这个动作抛出一个404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆