add consecutive numbering to field stating in 1 Rails + Postgresql

Viewed 22

current behavior

I want the topic_order field starting from 1, currently it sorted from first to last but start anywhere, I want a migration to bulk update all the topics so it starts from 1 until n. I could make:

def change
 i=1
 Topic.all.each do |topic|
  topic.update(topic_order: i)
  i += 1
 end
end

But is not efficient, I got hundreds of topics, Is there any way to make it better and faster? Thanks in advance

1 Answers

You can change the default in a migration:

def change
  execute "SELECT setval('products_id_seq', 1)"
  change_column :topics, :topic_order, :integer, default: -> { "nextval('topic_id_seq')" }
end

Hope this will help you.

Related