0

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
2
  • What error are you getting? Also, change Books to Book Commented Feb 23, 2017 at 7:24
  • It could not move if I thought the script would work. And I tried changed one it also doesn't work. Commented Feb 23, 2017 at 7:29

1 Answer 1

2

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.
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.