How to make this action throw a 404?

淺唱寂寞╮ 提交于 2019-12-24 02:56:27

问题


I have the following action:

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

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

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

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

I'm running Rails 3.2.1.


回答1:


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

raise ActiveRecord::RecordNotFound if @video.blank?

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])



来源:https://stackoverflow.com/questions/9703766/how-to-make-this-action-throw-a-404

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!