Multiple Paperclip default_urls

大城市里の小女人 提交于 2019-12-04 15:58:05

问题


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


回答1:


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



回答2:


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.



回答3:


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!




回答4:


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.



来源:https://stackoverflow.com/questions/1909547/multiple-paperclip-default-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!