1

I am using Paperclip to upload an image to my Project model and I want to have an array of default images (not depending on the style, but different images) is that posible? To pass an array instead of just one URL to the :default_url option?

Thank you,

Nicolás Hock Isaza

Hock
  • 5,784
  • 2
  • 19
  • 25

4 Answers4

4

So close: If you want the images to change randomly, and not just on first load of the model:

:default_url => lambda { "path/to/images/#{rand(5)}.jpg" }
bouchard
  • 820
  • 10
  • 27
3

Putting rand(5) in the default_url proc will assign a random image every time a new model object is created.

If you want the images to be randomly assigned and that each Project should keep their assigned image, you can do this:

has_attached_file :something,
  :default_url => lambda { |av| "/images/img_#{av.instance.default_image_number}.png" }

def default_image_number
  id.to_s.last
end

This example allows you to have 10 somewhat random default images that stay the same for each record:

# img_0.png, img_1.png, etc.
tee
  • 4,149
  • 1
  • 32
  • 44
1

Well I didn't use the lambda function but I got the idea from Ben's answer. I just have the files (0.jgp, 1.jpg ...) and then I can just have

:default_url => "path/to/images/#{rand(5)}.jpg"

With no lambda ;-)

Thank you very much!

Hock
  • 5,784
  • 2
  • 19
  • 25
  • 1
    Are the images switching randomly? I would expect that the rand() value would be interpreted only the first time the model is loaded. Try running it in production and seeing if the image switches. – Ben Dec 15 '09 at 19:21
  • They don't switch randomly, only on the first time the model is loaded as you expected. – jaacob May 10 '10 at 20:03
  • They will definitely switch randomly every time a new model is loaded, which would be every page load, for example. – tee Oct 18 '11 at 21:57
0

No idea if this will work, but it's worth a try. Put the images 0.png, 1.png, 2.png, 3.png, 4.png on disk, and then in your model:

has_attached_file :image,
  lambda {{
    :default_url => "path/to/images/#{rand(5)}.png"
  }}

Put your other options in the lambda as well.

Ben
  • 6,857
  • 26
  • 23
  • I tried to make this work but got `unexpected '\n', expecting tASSOC`. Not sure where the syntax error is. – jaacob May 10 '10 at 20:03