What's the difference between find, where and find_by_id?

后端 未结 4 741
余生分开走
余生分开走 2020-12-14 00:01

What\'s the difference between find, where and find_by_id? They all work when you try to find a user given an ID.

4条回答
  •  佛祖请我去吃肉
    2020-12-14 00:09

    find => This return single record if the given primary_key(id) exists in the system otherwise in will give an error.

    Model.find(required_id_value)
    

    find_by => This will return single record depends on the given attribute, and if the value of the attribute is not exist in the DB it will return nil.

    Model.find_by_name("your name")
    

    name here is the attribute and it must be exist in your Modal.

    where => This will 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
    

提交回复
热议问题