Skip to content

Instantly share code, notes, and snippets.

@skyporter
Last active September 2, 2020 14:26
Show Gist options
  • Save skyporter/0760a8a277ea05fd5fe545bc3dab337c to your computer and use it in GitHub Desktop.
Save skyporter/0760a8a277ea05fd5fe545bc3dab337c to your computer and use it in GitHub Desktop.
get recursive position
def position_titles
columns = %w"id parent_item_id title position"
columns_joined = columns.join(",")
sql = <<-SQL.squish
WITH RECURSIVE agenda_item_tree(#{columns_joined}, level)
AS (
SELECT #{columns_joined}, 0
FROM agenda_items
WHERE id = #{id}
UNION
SELECT #{columns.map { |col| 'agenda_items_2.' + col }.join(',')}, ct.level + 1
FROM agenda_items agenda_items_2, agenda_item_tree ct
WHERE agenda_items_2.id = ct.parent_item_id
) SELECT *
FROM agenda_item_tree
SQL
AgendaItem.find_by_sql(sql).map { |agenda_item| [agenda_item.title, agenda_item.position] }.reverse
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment