【问题标题】:Coalesce with baby_squeel / arel in Rails在 Rails 中与 baby_squeel / arel 合并
【发布时间】:2017-12-06 14:55:47
【问题描述】:

我正在尝试使用baby_squeel 编写一个相当复杂的查询。该查询需要使用coalesce SQL 函数。 coalesce 在 baby_squeel 主页上多次用作示例,但是当我尝试在查询中使用它时,我得到一个 no method 错误。

下面的例子:

result = Table.selecting { |t| [t.col1, 
                                ((coalesce(t.col2, 0) + coalesce(t.col3, 0)).sum.as('column'))] }
              .where.has { |t| t.col4 == 'some condition' }
              .grouping { |t| t.col1 }

我正在使用 Rails 5 和 baby_squeel 1.2。该查询在私有控制器函数内部调用。

为什么会这样?我是否需要 require 或使用 arel 自己定义函数?

【问题讨论】:

    标签: ruby-on-rails arel coalesce squeel


    【解决方案1】:

    不确定这是否会帮助任何人,但我找到了我所缺少的。由于我给块提供了 arity,因此我必须在这种情况下引用我想与 airty 变量一起使用的函数t。正确的代码是:

    result = Table.selecting { |t| [t.col1, 
                                    ((t.coalesce(t.col2, 0) + t.coalesce(t.col3, 0)).sum.as('column'))] }
                  .where.has { |t| t.col4 == 'some condition' }
                  .grouping { |t| t.col1 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多