有没有办法让ARel
将(清理过的,可能是别名的等)列名写入CONCAT()
和其他SQL函数?
这是how to do it with 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`"
(是的,我知道avg_id
在每一行都是一样的,只是试图说明我的问题)
那么如果我想要一个不同的功能呢?
?> Country.select(xyz).to_sql # Arel::Concat.new(name, population) or something?
=> "SELECT CONCAT(`countries`.`name`, ' ', `countries`.`population`) AS concat_id FROM `countries`"
谢谢!
答案 0 :(得分:12)
使用NamedFunction
:
name = Arel::Attribute.new(Arel::Table.new(:countries), :name)
func = Arel::Nodes::NamedFunction.new 'zomg', [name]
Country.select([name, func]).to_sql
答案 1 :(得分:0)
您还可以使用 Arel Extensions gem 来更简单地访问函数。
> User.where((User[:login] + User[:first_name]).length.in 2..10).to_sql
"SELECT `users`.* FROM `users`
WHERE LENGTH(CONCAT(CAST(`users`.`login` AS char),
CAST(`users`.`first_name` AS char)))
BETWEEN (2) AND (10)"