我尝试在Rails控制台中存储本地图像。
因为我有很多图片存储在本地(我使用爬虫下载了大量图片),我希望将它们存储到数据库中,借助 Paperclip 进行一些图像处理工作,如缩略图等。 如果我使用网页逐个保存新图片到数据库,这将耗费大量时间。所以我想在 Rails 控制台中找到一种批量将图片保存到数据库的方式(代码)。
我尝试在Rails控制台中存储本地图像。
因为我有很多图片存储在本地(我使用爬虫下载了大量图片),我希望将它们存储到数据库中,借助 Paperclip 进行一些图像处理工作,如缩略图等。 如果我使用网页逐个保存新图片到数据库,这将耗费大量时间。所以我想在 Rails 控制台中找到一种批量将图片保存到数据库的方式(代码)。
YourPaperclippedModelHere.new(:your_paperclip_field => File.new(path, "r"))
因此,如果您的模型名为Image,而您的Paperclip字段为data:
Image.new(:data => File.new(path_to_your_file, "r"))
class User < ActiveRecord::Base
has_attached_file :avatar
end
那么从控制台运行以下内容应该可以正常工作:
>> User.create(:avatar => File.open('/path/to/image.jpg', 'rb'))
File.open
参数中的 'rb'
和 'r'
是可以互换使用的,详情请见:https://dev59.com/C2w05IYBdhLWcg3wsz0l#7085623。 - Joshua PinterImage.new :data=>File.new("/path/to/image.jpg","r")
start' from /home/mlzboy/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.1/lib/rails/commands/console.rb:8:in
start'
from /home/mlzboy/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.1/lib/rails/commands.rb:23:in <top (required)>' from script/rails:6:in
require'
from script/rails:6:in `<main>' - mlzboyImage.create(:data => File.open('/path/to/image.jpg', 'r'))
- MageshImage
并没有内置在Ruby或Rails中;它是一个模型,就像应用程序中的User
或Post
一样需要定义。这里的Image
被用作ActiveRecord模型的示例。 - Luke GriffithsFile.new("#{Rails.root}/public/images/default_avatar.png", "r")