ruby-on-rails - 如果可能,find_by 是否总是返回条件数组中第一个的匹配项?

标签 ruby-on-rails ruby rails-activerecord

我想找到一个 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/

相关文章:

mysql - Rails ActiveRecord 处理一个不是主键的 id 列

javascript - 在数字字段中放置逗号

ruby-on-rails - Heroku pgbackups :restore rebuild the database or just repopulate it?

在 Rails 应用程序中多次触发 Javascript 事件?

ruby - 如何仅在`<legend>tax</legend> 时获取 `HREF` 值?

ruby-on-rails - 我得到 "Missing these required gems",但安装了 gem

ruby-on-rails - spree 商务谷歌分析更新

ruby-on-rails - 负载测试期间 Unicorn CPU 使用率激增,优化方法

Ruby 文件列表排除一个文件夹

ruby-on-rails - Postgresql:比较数组导致 "malformed array literal"错误