Shpigford
Shpigford

Reputation: 25338

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.

Upvotes: 3

Views: 5143

Answers (1)

James
James

Reputation: 4807

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

Upvotes: 14

Related Questions