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?
ActiveRecord::Base.find always throws an exception if it does not find a record, this is intentional. You should only use
findif 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
idattribute without forcing an exception, use the dynamic finderfind_by_idwhich will return false if it doesn’t find a record with that id.Edit:
Dynamic finders now have a different signature,
find_by_idshould now be:find_by :id, id_to_findSee the new Rails Guide on Querying