Rails 2: Model.find(1) gives ActiveRecord error when id 1 does not exist

后端 未结 8 1410
無奈伤痛
無奈伤痛 2020-11-28 12:03

I am using Rails 2.3.5 and in that if I give Model.find(1) and if 1 is not in the database, it returns ActiveRecord error. Should it just be returning nil

相关标签:
8条回答
  • 2020-11-28 12:35

    You can check if the record exists before fetching it.

    @model = Model.find(id) if Model.exists?(id)
    
    0 讨论(0)
  • 2020-11-28 12:37

    You can use find_by with the required attribute (in your case the id) this will return nil instead of giving an error if the given id is not found.

    Model.find_by_id(id_value)
    

    You could also use where but you have to know that where return an active record relation with zero or more records you need to use first to return only one record or nil in case zero records return.

    Model.where(id: id_value).first
    
    0 讨论(0)
提交回复
热议问题