我有一个Books
表,其中author_name
列是一个字符串
我有一个Author
表,我希望根据author_name
填充。
author_id
。
除了rake任务可以多次运行之外,将其写成以下内容有什么好处:
迁移:
class MoveAuthorDataToAuthors < ActiveRecord::Migration
def up
Book.all.each do |book|
first_name, last_name = book.author_name.split(' ')
Author.find_or_create_by(first_name: first_name, last_name: last_name).books << book
end
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
耙
作为rake任务,它可能看起来像
namespace :update_author_tabledb do
desc "Move Author Data To Authors"
Book.all.each do |book|
first_name, last_name = book.author_name.split(' ')
Author.find_or_create_by(first_name: first_name, last_name: last_name).books << book
end
end
end
控制台
在我的rails控制台中,我可以这样做:
Book.all.each do |book|
first_name, last_name = book.author_name.split(' ')
Author.find_or_create_by(first_name: first_name, last_name: last_name).books << book
end