0

I have a rails table. (normalusers)=> id, parent_id, Height. I have added the height column afterward. Now I want to add value to it. Is there any way I can achieve this? I have tried migration but it is not updating heights. I think functions do not work in migration. After migration, all the rows have the value of height same as before.

class Latest < ActiveRecord::Migration[6.0]

  def change
      i = 1
    loop do
          i += 1
          puts i
          record=Normaluser.find(i)
          record.height=get_height(record)
          record.save!
          if i == 39
            break       # this will cause execution to exit the loop
          end
    end
  end
  def get_height(record)
      maxHeight=0
      Normaluser.where(pid: record.id).each do |f|
          tempHeight=get_height(f)
          if tempHeight > maxHeight
              maxHeight=tempHeight
          end     
      end
      return maxHeight
  end
end
6
  • Please mention what is not working? Is there any error that you are facing? Commented Feb 10, 2020 at 14:45
  • @Gautam is this understandable? Commented Feb 10, 2020 at 14:53
  • Yes, there is nothing wrong in writing functions. I think you should debug to see that the value received from get_height function is correct. Commented Feb 10, 2020 at 15:05
  • @Gautam Where to see the output of put statement? It is not visible in the terminal. Commented Feb 10, 2020 at 16:48
  • 1
    You should be able to see the output of the puts statement when you run the migration. Commented Feb 10, 2020 at 16:56

1 Answer 1

1

The best way to run a one time script to update existing columns of a table is to write a rake task.

in lib/tasks/ directory, create a file named update_height.rake, in that file

namespace :update_latest_records do
  desc 'Update height column of existing Latest'
  task height: :environment do
    # your update logic goes here
  end
end

Then in project home, run the rake command

RAILS_ENV=development rake update_latest_records:height

Pass correct RAILS_ENV value in each environment, e.g. to update the records in production server it should be RAILS_ENV=production

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.