Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Rails find deprecated?

Is Rails find method deprecated?

In the olden days, find(1) was the preferred way to find by id.

Is it better to use find_by(id:1) instead of find(1)?

like image 559
B Seven Avatar asked Sep 26 '15 00:09

B Seven


2 Answers

Neither method is deprecated (as far as I know). The difference between find and find_by() is what they return when a record does not exist. If a record with an ID of 23 does not exist, this is what you get:

Model.find(23)
=> ActiveRecord::RecordNotFound: Couldn't find Model with 'id'=23

Or

Model.find_by(id: 23)
=> nil

Using find_by is more forgiving if you're making queries where a non-existent record is possible because you get a nil value rather than an exception.

like image 195
JeffD23 Avatar answered Oct 22 '22 05:10

JeffD23


Probably you are referring to the deprecation of ActiveRecord::Base#find like find(:first) and find(:all) that are deprecated in favor of first and all methods.

Support for this methods has been removed from rails 3.2.

The method you've used (ActiveRecord::FinderMethods#find) is not deprecated .

like image 44
Delian Avatar answered Oct 22 '22 04:10

Delian