Paperclip: How to store a picture in a Rails console?
Asked Answered
T

4

38

I tried storing a local image in a rails console.

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.

Trip answered 13/1, 2011 at 12:52 Comment(1)
I recommend taking more time with your question, including what you've tried and why you want to use "console" to store a local image... you'll get a higher chance of a reply by taking more time yourself.Northwesterly
S
56

To further clarify @andrea's answer:

YourPaperclippedModelHere.new(:your_paperclip_field => File.new(path, "r"))

So if your model is called Image and your paperclip field is data:

Image.new(:data => File.new(path_to_your_file, "r"))

Shelley answered 3/6, 2011 at 20:52 Comment(0)
N
19

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'))
Nonappearance answered 4/2, 2011 at 17:55 Comment(1)
For those that are curious, 'rb' and 'r' in the File.open parameter are interchangable, as per: https://mcmap.net/q/410680/-file-opening-mode-in-rubyGigahertz
H
2

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.

Image.new :data=>File.new("/path/to/image.jpg","r")
Hollandia answered 13/1, 2011 at 16:43 Comment(4)
ruby-1.9.2-p0 > Image.new NameError: uninitialized constant Image from (irb):2 from /home/mlzboy/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.1/lib/rails/commands/console.rb:44:in 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>'Trip
i tried use Image.new in rails console but it raise errors like aboveTrip
In this case the File.new doesn't work, instead you shoult try this Image.create(:data => File.open('/path/to/image.jpg', 'r'))Rapprochement
For future readers: Image is not built into Ruby or Rails; it is a model which would have to be defined just like User or Post in the app. Image here is being used as an example of an ActiveRecord model.Mekka
C
2

Late Answer but hopefully it will work for others. You need to include.

File.new("#{Rails.root}/public/images/default_avatar.png", "r")

Cardiogram answered 11/11, 2017 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.