← Back to Upcase

Add data to a new column for existing records

(Scott Hollinshead) #1

I have a Companies model that has 3 columns name update_at and created_at

I have just added an image column and I have a seed.rb file:

Company.create_with(image: image1.jpg").find_or_create_by(name: "company1")
Company.create_with(image: "image2.jpg").find_or_create_by(name: "company2")
Company.create_with(image: "image3.jpg").find_or_create_by(name: "company3")
Company.create_with(image: "image4.jpg").find_or_create_by(name: "company4")
Company.create_with(image: "image5.jpg").find_or_create_by(name: "company5")

How do i populate records that were created before adding the image column with the correct image name?


(Jose Alvarez) #2

Hi @scott, do you want a default image? or do you have a particular image for every case?

If it’s the first case, then you can take two approaches:

  1. Make an script to do it, and run it directly in rails console, like:
Company.all.each do |company|
  company.update_attribute(:image, 'default_image.jpg') unless company.image
  1. Put the script in the migration file, like:
def up
  add_column :companies, :image, :string
  Company.all.each do |company|
    company.update_attribute(:image, 'default_image.jpg') unless company.image

If it’s the second case, then you should probably do it manually in rails console. Or you can create an script to it with a hash having the keys as the company’s name and the value to be the image name, like:

companies_images = { 
  'company1' => 'image1.jpg', 
  'company2' => 'image2.jpg'

Company.all.each do |company|
  company.update_attribute(:image, companies_images[company.name]) unless company.image

(Scott Hollinshead) #3

@Jose_Alvarez Thank you very much the last one is what I need :smile:

How do you run scripts in the rails console?

(Jose Alvarez) #4

You can use:

bundle exec rails runner "eval(File.read 'your_script.rb')"

Or you can just copy and paste the script in the rails console.

To open rails console just run
$ rails console

(Bruno Bruno) #5

I’d advise creating a rake task and save it on lib/tasks/add_image_to_companies.rake.

desc 'Add image to companies'
task :add_image_to_companies => :environment do
  companies_images = { 
    'company'  => 'image1.jpg', 
    'company2' => 'image2.jpg'

  Company.where(image: nil).find_each(batch_size: 50) do |company|
    company.update_attribute(:image, companies_images[company.name])

And the you just need to run

$ rake add_image_to_companies