Dav*_*mpy 1 activerecord default ruby-on-rails coalesce arel
我继承了一个从多个表中提取的大型复杂 Arel 查询。一个新的要求是,如果这些表中的一个没有特定字段(“地区”)的值,我应该将其默认为“全局”。
由于查询构建和视图中的高度抽象,我没有什么好方法可以在查询之前或之后插入该默认值。因此,如果字段为零或没有匹配的行,我需要在 Arel 查询中的字段中插入一个默认值。
如何在 Arel 查询中将字段默认为字符串值?
我在网上找到了所有的碎片,但没有找到所有的部分粘在一起,所以我在这里分享,所以我下次可以再次找到它!
SQL'scoalesce用于提供默认值。
为了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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |