ironsand ironsand - 6 months ago 7
Ruby Question

Does find_by always return a match to the first of an array of conditions if possible?

I want to find a

Post
model whose
title
is "foo", but, if the post doesn't exist, "bar" and then "foobar".

For that I wrote this:

Post.find_by(title: %w(foo bar foobar))


It seems to be working fine now, but I'm not sure if the
find_by
method always finds the first value in the array of strings first.

When there are posts whose titles are
"foo"
and
"bar"
, does the code above always return the post with the title
"foo"
?

Answer

The order of alternatives doesn't matter. Per the documentation, find_by

Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself.

If you want the posts in a particular order, you'll have to either add an order clause to the query, e.g. in MySQL

Post.order("case title when 'foo' then 0 when 'bar' then 1 when 'foobar' then 2 end").
  find_by(title: %w(foo bar foobar))

or sort the Posts afterwards:

titles = %w(foo bar foobar)
Post.find_by(title: titles).sort_by { |post| titles.index post.title }
Comments