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.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
mlzboy
  • 14,343
  • 23
  • 76
  • 97
  • 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. – Jesse Wolgamott Jan 13 '11 at 16:40

4 Answers4

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"))

ZiggyTheHamster
  • 873
  • 8
  • 14
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'))
artemave
  • 6,786
  • 7
  • 47
  • 71
  • For those that are curious, `'rb'` and `'r'` in the `File.open` parameter are interchangable, as per: http://stackoverflow.com/a/7085623/293280 – Joshua Pinter Jun 18 '15 at 14:25
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")
andrea
  • 3,515
  • 2
  • 22
  • 14
  • 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 `' from script/rails:6:in `require' from script/rails:6:in `
    '
    – mlzboy Jan 14 '11 at 02:55
  • i tried use Image.new in rails console but it raise errors like above – mlzboy Jan 14 '11 at 02:56
  • In this case the File.new doesn't work, instead you shoult try this `Image.create(:data => File.open('/path/to/image.jpg', 'r'))` – Magesh Aug 06 '12 at 07:51
  • 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. – Luke Griffiths Apr 29 '15 at 20:10
2

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

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

Ahmad
  • 413
  • 5
  • 12