Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is rails 4 find_by deprecated?

I heard that find_by is deprecated is this true? I have been thinking of alternatives such as creating for each find a different method, e.g.:

before:

Model.find_by_username 'username'

after: --in model---

class << self
   def by_username username
      where(:username => username).first 
   end
end

is it a good naming? what names do you give for such methods?

Update:

find_by is not deprecated but the announcement could have been clearer!

like image 448
reizals Avatar asked May 28 '14 21:05

reizals


2 Answers

According to the Rails 4 Release Notes:

All dynamic methods except for find_by_... and find_by_...! are deprecated.

find_by is not a dynamic method and therefore it's NOT DEPRECATED, and find_by_... & find_by_...! are dynamic, but still not deprecated as mentioned above.

So that means you still can use the original methods provided by Active Record without having to define your own:

Model.find_by_username(:username)
Model.find_by(username: 'value', age: 24)


If you want the functionality of the really deprecated finder methods you can either include the gem that they were moved into: activerecord-deprecated_finders. Or follow what the Rails 4 Release Notes say:

Here's how you can rewrite the code:

  • find_all_by_... can be rewritten using where(...).
  • find_last_by_... can be rewritten using where(...).last.
  • scoped_by_... can be rewritten using where(...).
  • find_or_initialize_by_... can be rewritten using find_or_initialize_by(...).
  • find_or_create_by_... can be rewritten using find_or_create_by(...).
  • find_or_create_by_...! can be rewritten using find_or_create_by!(...).
like image 159
Tamer Shlash Avatar answered Nov 16 '22 05:11

Tamer Shlash


I would avoid cluttering your model with such methods. Also, Rails still provides the find_by method. Thus I think a better solution would be

Model.find_by(username: 'whatever_username')
like image 42
Bart Jedrocha Avatar answered Nov 16 '22 05:11

Bart Jedrocha