Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I skip an error if find returns nothing in rails?

I am trying to make a system where user can only see articles that he or she wrote.

In Articles controller, I put below line

@article = current_user.articles.find(params[:id])

where params[:id] is an article_id.

I just want to know how I can skip the error from displaying and just redirect to the :index action if article does not exist, or if user does not have permission to view it. I put @article.nil? conditional statement after above find statement, but it seems that the find statement above produces the error immediately like below.

Couldn't find Article with ID=1662 [WHERE (articles.user_id = 1)]

How can I resolve this problem?

like image 228
user482594 Avatar asked Mar 24 '11 02:03

user482594


2 Answers

ActiveRecord::Base.find always throws an exception if it does not find a record, this is intentional. You should only use find if you absolutely expect to have whatever it is you're looking for. If you are rending a show action and can't find the article, you should rescue that exception and render a 404 (Not found) instead of redirecting to index (technically).

If you want to find something by it's id attribute without forcing an exception, use the dynamic finder find_by_id which will return false if it doesn't find a record with that id.

Edit:

Dynamic finders now have a different signature, find_by_id should now be:

find_by :id, id_to_find

See the new Rails Guide on Querying

like image 178
Brett Bender Avatar answered Oct 06 '22 00:10

Brett Bender


You should use find_by_id or any of the methods given in this question.

like image 42
rubyprince Avatar answered Oct 06 '22 00:10

rubyprince