问题
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