ironsand ironsand - 11 months ago 29
Ruby Question

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

I want to find a

model whose
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
method always finds the first value in the array of strings first.

When there are posts whose titles are
, does the code above always return the post with the title


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 }