Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't Rails find_by_ methods return an empty array instead of nil?

Shouldn't Rails find_by_ methods return an empty array instead of nil?

It's normal for there to be no records that match the find_by_ condition, but returning nil doesn't make sense. Because then in my views errors are raised by sensible 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's only 1 record, it should also return an array if there are 0 records. Then all those

<% @thing.each

and

<% for thing in @thing

in our views will quietly get passed over instead of causing a "We're sorry, but something went wrong." (or what am I missing? what's the current best practice of dealing with this?)

like image 217
Arcolye Avatar asked Sep 14 '11 04:09

Arcolye


1 Answers

find_by_ is used to find one record, the first one that matches your conditions.

find_all_by_ is used to find a set of records, an array, that match your conditions.

So, yes, I think it's totally normal for find_by_ to return nil, and not an empty array, when it doesn't find anything, because you're only asking for one thing.

like image 76
theIV Avatar answered Oct 21 '22 13:10

theIV