ruby-on-railsrubyarel

Rails Arel how group by select


I want firstly add attributes with select and then order by them.

label = Arel.sql(
    %q(
        case label
        when 'x' then 1
        when 'y' then 2
        end
    )
)

Item.all.select("*, 'x' as label").order(label)

Error:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column "label" does not exist)
LINE 2:       case label

Solution

  • Hard to figure out what the end result should be. You say GROUP BY, but I don't see what you're trying to group. I'm going to guess that you don't actually need to do this. You can also sort by multiple columns if that's what you're trying to do.

    If you have to use Arel

    Item.select(
          Arel.star, 
          Arel::Nodes::Case.new(Item.arel_table[:column_name]) 
           .when('x').then(1)
           .when('y').then(2)
           .as('label'))
        .order('label')
    

    otherwise just use plain strings, you don't need to wrap it in Arel

    Item.select("*")
        .select("CASE items.column_name WHEN 'x' THEN 1 WHEN 'y' THEN 2 END AS label")
        .order('label')
    

    Do the logic in SELECT then sort by the result.