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?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With