44298

How to make this action throw a 404?

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.

Answer1:

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

Recommend

  • Digging down json file
  • Create Virtual Directory IIS7 to be use in GetFolder in Server.CreateObject(“Scripting.FileSystemObj
  • iOS: define and use C++ in Objective-C++
  • afterSetExtremes callback for highcharts
  • How to store pointer to S3 objects in Amazon SimpleDB?
  • Open Video file in VLC through Python
  • Disable Application from sleeping in Windows 8 Metro
  • How to create a jQuery price slider
  • Do custom action after devise model confirmation
  • iPhone: 5 seconds video capture
  • Publishing HTML Field Control Converts Relative URL to Absolute URL
  • Youtube Video Player Fullscreen click event
  • Add a div to replace Video after Video Plays Through
  • Are there any supported high bit-depth video or image formats in DirectShow
  • Converting raw frames into webm live stream
  • Wrap C++ function using Boost Reflect or another C++ reflection library
  • android Navigation Bar hiding and persantage of usable screen overlap
  • SIP API media codecs
  • How can the INSERT … ON CONFLICT (id) DO UPDATE… syntax be used with a sequence ID?
  • Marklogic : Query response time is very high
  • Rails Find when some params will be blank
  • Why querying a date BC is changed to AD in Java?
  • Record samples being played with OpenAL
  • Why value captured by reference in lambda is broken? [duplicate]
  • Sending data from AppleScript to FileMaker records
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Load html files in TinyMce
  • Why joiner is not used after Sequence generator or Update statergy
  • How to stop GridView from loading again when I press back button?
  • How can I remove ASP.NET Designer.cs files?
  • python draw pie shapes with colour filled
  • Can't mass-assign protected attributes when import data from csv file
  • Is there any way to bind data to data.frame by some index?
  • Recursive/Hierarchical Query Using Postgres
  • How can i traverse a binary tree from right to left in java?
  • UserPrincipal.Current returns apppool on IIS