我想找到一个 Post
模型,其 title
是“foo”,但是,如果该帖子不存在,则为“bar”,然后是“foobar”。
为此我写了这个:
Post.find_by(title: %w(foo bar foobar))
现在看起来工作正常,但我不确定 find_by
方法是否总是首先找到字符串数组中的第一个值。
当有标题为 "foo"
和 "bar"
的帖子时,上面的代码是否总是返回标题为 "foo"< 的帖子
?
最佳答案
备选方案的顺序无关紧要。 Per the documentation , 查找方式
Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself.
如果您希望帖子按特定顺序排列,您必须要么
在查询中添加一个
order
子句,例如Post.order("case title when 'foo' then 0 when 'bar' then 1 when 'foobar' then 2 end"). find_by(title: %w(foo bar foobar))
在 MySQL 中测试;不确定这种语法有多普遍,但至少在任何 SQL 数据库中都应该有类似的东西。
您可能需要动态构建
order
子句。来自 ironsand 在评论中的解决方案:titles = %w(foo bar foobar) order_sql = "case #{titles.map.with_index { |title, i| "when '#{title}' then #{i}" }.join ' ' } end" Post.order(order_sql).find_by(title: titles)
查询所有帖子,然后排序
Post.all.sort_by { |post| %w(foo bar foobar).index post.title }.first
这对于大量的帖子来说会很慢,所以它是否有用可能取决于您是否可以从比
Post.all
更具体的东西开始。
关于ruby-on-rails - 如果可能,find_by 是否总是返回条件数组中第一个的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37153671/