I have the following SQL which recursively gets all of the parents of a record using WITH RECURSIVE
. What would the equivalent of this be in Arel?
table_name = self.class.table_name
arel_table = self.class.arel_table
sql = <<-SQL
WITH RECURSIVE a AS (
SELECT * FROM #{table_name} WHERE id = '#{id}'
UNION ALL
SELECT b.* FROM #{table_name} b
JOIN a ON b.id = a.parent_id
) SELECT id FROM a
SQL
ids = ActiveRecord::Base.connection.execute(sql).field_values('id')
ordering = ids.map { |id| arel_table[:id].eq(id) }
self.class.where(id: ids).order(ordering)
After taking a look at the test that @cschroed pointed me to I was able to refactor my raw SQL into: