Reputation: 39
The Book model have
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
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|
Upvotes: 2