Should the Rails find_by_ methods return an empty array instead of nil?

Should the Rails find_by_ methods return an empty array instead of nil?

It is normal that there are no entries matching the find_by_ condition, but returning nil does not make sense. Because then, in my views, errors are raised by reasonable code like:

<% for thing in @thing_that_might_be_an_array_or_might_be_nil do %> 

Since find_by_ always returns an array, even if there is only 1 record, it should also return an array if there are 0 records. Then all these

 <% @thing.each 

and

 <% for thing in @thing 

in our ideas it will be calmly conveyed instead of calling "We are sorry, but something went wrong." (or what am I missing?) What is the current best practice for dealing with this?)

+6
source share
1 answer

find_by_ used to search for a single record, the first of which matches your criteria.

find_all_by_ used to search for a set of records, an array that matches your conditions.

So yes, I find it absolutely normal for find_by_ return nil, not an empty array when it does not find anything, because you are only asking for one thing.

+6
source

Source: https://habr.com/ru/post/897283/


All Articles