如何在ARel中使用CONCAT()等函数?

时间:2021-12-20 22:53:33

Is there a way to have ARel write (sanitized, possibly aliased, etc.) column names into CONCAT() and other SQL functions?

有没有办法让ARel写入(清理,可能是别名等)列名到CONCAT()和其他SQL函数中?

Here's how to do it with AVG()...

以下是使用AVG()的方法...

?> name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
=> #<struct Arel::Attributes::Attribute [...]
?> population = Arel::Attribute.new(Arel::Table.new(:countries), :population)
=> #<struct Arel::Attributes::Attribute [...]
?> Country.select([name, population.average]).to_sql
=> "SELECT `countries`.`name`, AVG(`countries`.`population`) AS avg_id FROM `countries`"

(yes, I know that avg_id would be the same in every row, just trying to illustrate my question)

(是的,我知道avg_id在每一行都是一样的,只是试图说明我的问题)

So what if I wanted a different function?

那么如果我想要一个不同的功能呢?

?> Country.select(xyz).to_sql # Arel::Concat.new(name, population) or something?
=> "SELECT CONCAT(`countries`.`name`, ' ', `countries`.`population`) AS concat_id FROM `countries`"

Thanks!

1 个解决方案

#1


12  

Use NamedFunction:

name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
func = Arel::Nodes::NamedFunction.new 'zomg', [name]
Country.select([name, func]).to_sql

#1


12  

Use NamedFunction:

name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
func = Arel::Nodes::NamedFunction.new 'zomg', [name]
Country.select([name, func]).to_sql