Search code examples
rubyarel

How to use Arel::Nodes::NamedFunction to define GROUP_CONCAT with SEPARATOR option


I defined a named Arel function for MariaDB's GROUP_CONCAT

ta = Arel::Table.new 'authors'

Arel::Nodes::NamedFunction.new( 'GROUP_CONCAT',  [ta[:name]] ).to_sql

This generates:

"GROUP_CONCAT(`authors`.`name`)"

I like however to define the separator option to generate the following output:

"GROUP_CONCAT(`authors`.`name` SEPARATOR '|' )"

I tried a number of approaches, for example

Arel::Nodes::NamedFunction.new( 'GROUP_CONCAT',  [ ta[:name]], "SEPERATOR |"  ).to_sql

Doesn't work since it creates the following SQL snippet:

GROUP_CONCAT(`authors`.`name`) AS SEPERATOR '|'

How do I need to specify the parameters for the desired output?

Many thanks :)


Solution

  • you nearly had it. All of the arguments go into the array (second argument). AFAIK, Arel has always been considered a private API, so documentation is pretty sparse.

    (https://github.com/rails/rails/blob/354f1c28e81d9846fb9e5346fcca50cf303c12c1/activerecord/lib/arel/nodes/named_function.rb)

    Arel::Nodes::NamedFunction.new('GROUP_CONCAT', [ta[:name], Arel.sql("SEPARATOR '|'")]).to_sql