Ruby-on-rails 回形针:如何在 Rails 控制台中存储图片?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4680265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Paperclip: How to store a picture in a Rails console?
提问by mlzboy
I tried storing a local image in a rails console.
我尝试在 rails 控制台中存储本地图像。
Because I have many pictures in my local storage (I use crawler to download tons of pictures), I want to store them into a database, with the benefit of paperclip to do some image job, like thumbnail etc. If I use a webpage to save new pictures to database one by one, it will cost a lot of time. So I want to find a way in rails console (some code) that can batch save-picture-into-database.
因为我的本地存储中有很多图片(我使用爬虫下载了大量图片),我想将它们存储到数据库中,利用回形针做一些图像工作,例如缩略图等。 如果我使用网页来将新图片一张一张地保存到数据库中,这会花费很多时间。所以我想在rails控制台(一些代码)中找到一种可以批量保存图片到数据库的方法。
回答by ZiggyTheHamster
To further clarify @andrea's answer:
为了进一步澄清@andrea 的回答:
YourPaperclippedModelHere.new(:your_paperclip_field => File.new(path, "r"))
YourPaperclippedModelHere.new(:your_paperclip_field => File.new(path, "r"))
So if your model is called Image and your paperclip field is data:
因此,如果您的模型名为 Image 而您的回形针字段是数据:
Image.new(:data => File.new(path_to_your_file, "r"))
Image.new(:data => File.new(path_to_your_file, "r"))
回答by artemave
If this is the model:
如果这是模型:
class User < ActiveRecord::Base
has_attached_file :avatar
end
then the following should work from the console:
那么以下应该从控制台工作:
>> User.create(:avatar => File.open('/path/to/image.jpg', 'rb'))
回答by andrea
I dont know if it is what you want ... but to save an paperclip asset from console You could simple use a File instance . a.e.
我不知道这是否是您想要的……但是从控制台保存回形针资产您可以简单地使用 File 实例。ae
Image.new :data=>File.new("/path/to/image.jpg","r")
回答by user3253756
Late Answer but hopefully it will work for others. You need to include.
迟到的答案,但希望它对其他人有用。你需要包括。
File.new("#{Rails.root}/public/images/default_avatar.png", "r")
File.new("#{Rails.root}/public/images/default_avatar.png", "r")

