johnny
johnny

Reputation: 39

how to run migration file with ruby script

The Book model have

  1. name column
  2. author column
  3. ad column (I want to add)

I would like to add 'Mr' to the name column and add them to the ad column. For that, I wanted to write a script with migration file, but it did not work. What should I do? Thanks

class AddAdToBooks < ActiveRecord::Migration
  def change
    add_column :books, :ad, :string

    Book.all.each do |book|
      book.ad = 'Mr.' + name
      book.save
    end
  end
end

Upvotes: 0

Views: 813

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

I this you can achieve that using raw query. It's always better to execute raw query unless you want to run the Model callbacks.

class AddAdToBooks < ActiveRecord::Migration
  def change
    add_column :books, :ad, :string

    if ActiveRecord::Base.connection.adapter_name.downcase.include? "mysql"
      execute "UPDATE books SET ad = CONCAT('Mr. ', name)"
    else
      execute "UPDATE books SET ad = 'Mr. ' || name"
    end
  end
end

The problem with the following

Book.all.each do |book|
  1. It will load all records even if you have 1 million records in memory and loop over it.
  2. Also, It will run all the callbacks for that model.

Upvotes: 2

Related Questions