Rails how to redirect if record is not found

前端 未结 5 1096
时光说笑
时光说笑 2021-02-05 05:42

I am trying to redirect if the record is not found. The page is not redirect and I get the error record not found.

My controller:

def index
@link = Link.         


        
5条回答
  •  长发绾君心
    2021-02-05 06:25

    Very tricky one ... I found a simple solution for this.... This solution works for me

    @link = Link.where(:id => params[:id]).first

    I am using .first because .where will return an array.Yes, of-course this array has only one element. So, When there is no record with such id, it will return an empty array, assign a blank element to @link ... Now check @link is either blank or not....

    Conclusion: No need to provide exception handling for a simple check It is problem with .find it throws exception when no record exist ... Use .where it will return an empty array

    And Sorry for my Bad English

提交回复
热议问题