【问题标题】:Arel - How to coalesce a field and a string literal in an Arel query?Arel - 如何在 Arel 查询中合并字段和字符串文字?
【发布时间】:2018-05-31 18:01:03
【问题描述】:

我继承了一个从多个表中提取的大而复杂的 Arel 查询。一项新要求是,如果其中一个表格没有特定字段(“地区”)的值,我应该将其默认为“全局”。

由于查询构建和视图中的高级抽象,我没有在查询之前或之后插入该默认值的好方法。因此,如果字段为 nil 或没有匹配的行,我需要在 Arel 查询中的字段中插入默认值。

如何在 Arel 查询中将字段默认为字符串值?

【问题讨论】:

    标签: ruby-on-rails activerecord default arel coalesce


    【解决方案1】:

    我在网上找到了这个的所有部分,但没有找到所有部分都粘在一起,所以我在这里分享,下次我可以再找到它!

    SQL 的coalesce 用于提供默认值。

    为了让coalesce 进入查询,我使用Arel::Nodes::NamedFunction。 NamedFunction 允许您引用 Arel 不知道的任何 SQL 函数。

    注意 SqlLiteral 字符串中的单引号。

    supplier_table = Supplier.arel_table
    
    district = Arel::Nodes::NamedFunction.new(
      'coalesce',
      [supplier_table[:district], Arel::Nodes::SqlLiteral.new("'Global'") ]
    ).as('district')
    
    ProductHistoryResult.joins(some_join, some_other_join).select(
      [this_arel, that_arel, the_other_arel, district]
    ).where(product_history_request_id: id)
    

    【讨论】:

    • 你可以使用Arel::Nodes::Quoted.new('Global') 让它更干净一些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2011-05-24
    • 2011-08-13
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多