我正在创建一个将执行以下 3 项操作的迁移:创建一个名为 images
的表,将所有图像从 products
表传输到新的 images
表,然后从 products
表中删除所有图像列。
除了传输图像部分外,一切正常。没有图像信息传输。
这是迁移:
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.belongs_to :product
t.string :image_file_name, :image_content_type
t.integer :image_file_size
t.boolean :main, :default => false
t.timestamps
end
Product.all.each do |product|
begin
product.images.create(:image => product.image, :main => true)
rescue => e
logger.warn "Error while transferring images from product: #{product.name} to Images: #{e}"
end
end
remove_column :products, :image_file_name
remove_column :products, :image_content_type
remove_column :products, :image_file_size
remove_column :products, :image_updated_at
add_index :images, [:product_id, :main]
end
end
最佳答案
您不应在 ActiveRecord 迁移中执行文件系统操作,如文件处理。这主要是因为 ActiveRecord 迁移是在数据库事务中执行的,如果是事务文件,则不会对文件进行更改。另外,如果您尝试处理大量文件,您可能会遇到意外的数据库连接超时或类似错误。
您必须在 lib 目录中创建一个 Rake 任务,并在迁移完成后运行它。此类 rake 任务应先将文件复制到新目录,然后删除旧文件。您可能会发现这篇文章有帮助:http://fernandomarcelo.com/2012/05/paperclip-how-to-move-existing-attachments-to-a-new-path/ .它不是特定于回形针的。
最后,在不同的迁移中运行 remove_column 语句。
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.belongs_to :product
t.string :image_file_name, :image_content_type
t.integer :image_file_size
t.boolean :main, :default => false
t.timestamps
end
end
end
在此处手动运行您的任务。
最后,执行下面的迁移。
class RemoveImagesFromProducts < ActiveRecord::Migration
def change
remove_column :products, :image_file_name
remove_column :products, :image_content_type
remove_column :products, :image_file_size
remove_column :products, :image_updated_at
add_index :images, [:product_id, :main]
end
end
关于ruby-on-rails - 如何创建将所有图像从一个表传输到另一个表的 Rails 迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481774/