I'm getting NoMethodError: undefined method relation' for <Arel::Nodes::NamedFunction:0x7633>
when trying to group by the results of a named function.
class Appointment < ActiveRecord::Base
scope :group_by_date, -> { group(date_column) }
def self.date_column
Arel::Nodes::NamedFunction.new(:date, [Appointment.arel_table[:start_time]], 'date')
end
end
Appointment.group_by_date.count
# results in NoMethodError: undefined method `relation' for #<Arel::Nodes::NamedFunction:0x7633>
This seems perfectly reasonable, so I'm not sure why it's creating an error. I'm pretty sure this was was possible in earlier versions of rails as indicated by this SO answer.
I'm expecting to get something akin to the following sql:
SELECT date(appointments.start_time) AS date, COUNT(appointments.*) AS count
FROM appointments
GROUP BY date(appointments.start_time)
Is there a way to get this to work? Is there a way to convert the Arel::Nodes::NamedFunction
to Arel::Attributes::Attribute
This is obviously a naive attempt at a solution (it didn't work):
function = Arel::Nodes::NamedFunction.new('date', [Appointment[:start_time]])
attr = Arel::Attributes::Attribute.new(function)
Appointment.group(attr).to_sql
# NoMethodError: undefined method `table_alias' for #<Arel::Nodes::NamedFunction:0x4b8>
I really don't want to have to drop back to using Appointment.group( 'date(appointments.start_time)' )
as I do a lot of scope merging and joining and string cause havoc as they don't always scope to the correct table.
Environment: rails (4.1.8), activerecord (4.1.8), arel (5.0.1.20140414130214)